【问题标题】:How use input and output file in Python如何在 Python 中使用输入和输出文件
【发布时间】:2015-11-08 21:52:50
【问题描述】:

我有一个 Python 脚本,它输入文件中的所有单词并按顺序对它们进行排序:

with open(raw_input("Enter a file name: ")) as f :
     for t in sorted(i for line in f for i in line.split()):
           print t

但不是每次都询问输入文件,我想选择带有“-i”的输入文件并使用“-o”保存输出文件,这样:

python myscript.py -i input_file.txt -o output_file.txt 

顺便说一句,如何将输出保存到目标文件中?

【问题讨论】:

    标签: python dictionary input output


    【解决方案1】:

    应该这样做:

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', dest='infile',
                        help="input file", metavar='INPUT_FILE')
    parser.add_argument('-o', dest='outfile',
                        help='output file', metavar='OUTPUT_FILE')
    args = parser.parse_args()
    
    with open(args.infile, 'r') as infile:
        indata = infile.read()
    
    words = indata.split()
    words.sort()
    
    with open(args.outfile, 'w') as outfile:
        for word in words:
            outfile.write('{}\n'.format(word))
    

    argparse 是一个用于解析命令行选项的内置模块。它为您完成所有工作。

    $ ./SO_32030424.py --help
    usage: SO_32030424.py [-h] [-i INPUT_FILE] [-o OUTPUT_FILE]
    
    optional arguments:
      -h, --help      show this help message and exit
      -i INPUT_FILE   input file
      -o OUTPUT_FILE  output file
    

    【讨论】:

    • 一切都好,但它给了我一个错误:我确实认为这种方式不是创建文件: Traceback(最近一次调用最后一次):第 15 行,在 中使用 open(args .outfile) as outfile: IOError: [Errno 2] No such file or directory: 'dest.txt'
    • 哎呀!我没有指定模式;固定。
    • 谢谢。我尝试添加“w”,但没有成功。你还改变了什么?我想学习。
    • @FrancescoMantovani,这就是我改变的全部。您能否将即使使用 'w' 也无法使用的代码粘贴到 pastebin 上?
    • 为时已晚。可能是因为'w'之前没有出现
    【解决方案2】:

    要开始使用您的参数,请查看sys.argv

    要写入输出文件,请使用写入模式“w”和.write()

    对于后者,肯定有很好的教程。

    【讨论】:

    • sys.argv 仅将裸参数作为列表,但不处理 -i 之类的标志。
    • 是的,你可以自己写。或者使用 argparse。
    猜你喜欢
    • 2012-06-04
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多