gpt4 book ai didi

python - 如何在Python中使用输入和输出文件

转载 作者:行者123 更新时间:2023-11-30 23:07:51 26 4
gpt4 key购买 nike

我有一个 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 

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

最佳答案

这应该可以做到:

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

关于python - 如何在Python中使用输入和输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32030424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com