我的输入文件看起来像 this (infile.txt):
a x
b y
c z
我想实现一个程序,使用户可以根据命令写入STDOUT或文件:
python mycode.py infile.txt outfile.txt
将写入文件。
用这个
python mycode.py infile.txt #2nd case
将写入STDOUT。
我坚持使用这段代码:
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: ''
实施它的更好方法是什么?
答案 0 :(得分:2)
你可以试试这个:
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
会很好。