如何实现标准输出和文件写入基于参数输入
我有一个看起来输入文件中像this(infile.txt):如何实现标准输出和文件写入基于参数输入
a x
b y
c z
我想要实现一个程序,允许用户写入STDOUT或文件取决于命令:
python mycode.py infile.txt outfile.txt
将写入文件。
而与此
python mycode.py infile.txt #2nd case
将写入标准输出。
我坚持用这个代码:
import sys
import csv
nof_args = len(sys.argv)
infile = sys.argv[1]
print nof_args
outfile = ''
if nof_args == 3:
outfile = sys.argv[2]
# for some reason infile is so large
# so we can't save it to data structure (e.g. list) for further processing
with open(infile, 'rU') as tsvfile:
tabreader = csv.reader(tsvfile, delimiter=' ')
with open(outfile, 'w') as file:
for line in tabreader:
outline = "__".join(line)
# and more processing
if nof_args == 3:
file.write(outline + "\n")
else:
print outline
file.close()
当使用第二种情况是产生
Traceback (most recent call last):
File "test.py", line 18, in <module>
with open(outfile, 'w') as file:
IOError: [Errno 2] No such file or directory: ''
什么来实现它的更好的办法?
你可以试试这个:
import sys
if write_to_file:
out = open(file_name, 'w')
else:
out = sys.stdout
# or a one-liner:
# out = open(file_name, 'w') if write_to_file else sys.stdout
for stuff in data:
out.write(stuff)
out.flush() # cannot close stdout
# Python deals with open files automatically
你也可以用这个来代替out.flush()
:
try:
out.close()
except AttributeError:
pass
这看起来有点丑到我,所以,flush
将是多么好。
你能说说我的例子for-loop和'sys.argv'吗? – neversaint
@neversaint,只要在循环内部调用'out.write'即可。 – ForceBru
@neversaint,以几乎相同的方式:打开文件以阅读或使用'sys.stdin',但不'flush'并使用答案中提供的第二种方法尝试关闭文件。你还应该用'write'代替'read'。 – ForceBru
当'nof_args == 2'时你是否将'outfile'定义为'stdout'?否则'打开(outfile,'w')作为文件:'会失败。 –
我看到你从你删除的问题中使用了我的'len(sys.argv)'。一旦你有答案,你有养成删除问题的习惯吗? –