【发布时间】:2014-12-05 14:24:47
【问题描述】:
我正在尝试读取通过命令行重定向标准输入的文本文件的内容,并在接收者必须将其组装回原始形式时通过 Internet 发送。
例如:
$ python test.py < file.txt
我已尝试读取该文件并使用以下受link 启发的代码将其组装回来:
for line in sys.stdin:
stripped = line.strip()
if not stripped: break
result = result + stripped
print "File is beeing copied"
file = open("testResult.txt", "w")
file.write(result)
file.close()
print "File copying is complete!"
但是只要我的文件中没有空行(两个 '\n' 一个接一个),这个解决方案就可以工作,如果我有,我的循环会中断并且文件读取结束。我该如何阅读从标准输入直到我到达被重定向的文件的?
【问题讨论】:
-
file.write(sys.stdin.read()) -
对于像我这样愚蠢的人,在你进入 SO 兔子洞之前,请确保你的终端与 .txt 文件位于同一目录中(否则它将运行一个空文件)。