我有一個看起來輸入文件中像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)'。一旦你有答案,你有養成刪除問題的習慣嗎? –