我有一个看起来输入文件中像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: ''
什么来实现它的更好的办法?
当'nof_args == 2'时你是否将'outfile'定义为'stdout'?否则'打开(outfile,'w')作为文件:'会失败。 –
我看到你从你删除的问题中使用了我的'len(sys.argv)'。一旦你有答案,你有养成删除问题的习惯吗? –