【问题标题】:I want to read in a file from the command line in python我想从 python 的命令行中读取一个文件
【发布时间】:2011-11-18 08:14:07
【问题描述】:

如何在命令行从 python 读取文件?所以假设我有一个text.txt 文件,我想做$ python prefixer.py text.txt,我将如何读取我的prefixer.py 中的文本文件?

【问题讨论】:

    标签: python command


    【解决方案1】:

    我认为fileinput 对此要好得多。易于使用的简单脚本:

    import fileinput
    for line in fileinput.input():
        process(line)
    

    然后你可以做python myscript.py file.txt 甚至管它。Purrfect!

    https://docs.python.org/3/library/fileinput.html

    【讨论】:

      【解决方案2】:
      import sys
      
      f = open(sys.argv[1],"r")
      contents = f.read()
      f.close()
      print contents 
      

      或者,更好,

      import sys
      with open(sys.argv[1], 'r') as f:
          contents = f.read()
      print contents
      

      【讨论】:

      【解决方案3】:
      import sys
      
      file_name = sys.argv[1]
      f = open(file_name)
      data = f.read()
      f.close()
      

      【讨论】:

      • 别忘了从sys导入argv
      • 如果你有更多的参数,你应该使用 OptParse 来读取参数。
      • 或 Python 3.2+ 上改进的argparse
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 2016-05-09
      • 2011-10-25
      • 2016-02-20
      相关资源
      最近更新 更多