2017-02-14 74 views
0

我有一個看起來輸入文件中像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: '' 

什麼來實現它的更好的辦法?

+0

當'nof_args == 2'時你是否將'outfile'定義爲'stdout'?否則'打開(outfile,'w')作爲文件:'會失敗。 –

+0

我看到你從你刪除的問題中使用了我的'len(sys.argv)'。一旦你有答案,你有養成刪除問題的習慣嗎? –

回答

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將是多麼好。

+0

你能說說我的例子for-loop和'sys.argv'嗎? – neversaint

+1

@neversaint,只要在循環內部調用'out.write'即可。 – ForceBru

+1

@neversaint,以幾乎相同的方式:打開文件以閱讀或使用'sys.stdin',但不'flush'並使用答案中提供的第二種方法嘗試關閉文件。你還應該用'write'代替'read'。 – ForceBru

相關問題