如何根据参数输入实现STDOUT和文件写入
How to implement STDOUT and file write based on parameter input
我的输入文件看起来像 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: ''
实施它的更好方法是什么?
你可以试试这个:
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
就好了。
我的输入文件看起来像 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: ''
实施它的更好方法是什么?
你可以试试这个:
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
就好了。