[英]Read a File from redirected stdin with python
我試圖通過命令行讀取重定向stdin的文本文件的內容,並在接收器必須將其組裝回原始形式時通過Internet發送它。
例如:
$ python test.py < file.txt
我試圖讀取該文件,並把它與靈感來自於下面的代碼匯編回鏈接 :
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'一個接一個)在我的文件中,如果我有,我的循環中斷和文件讀取結束。我怎樣才能從stdin讀取我到達重定向文件的<>?
為什么你甚至看數據:
result = sys.stdin.read()
而不是打破,你只想continue
下一行。 迭代器到達文件末尾時將自動停止。
import sys
result = ""
for line in sys.stdin:
stripped = line.strip()
if not stripped:
continue
result += stripped
line.strip()
從讀取行中刪除尾部換行符。
如果你想要那個新行,那么你不應該這樣做我不認為(你的輸出文件是否有輸入換行符)?
if stripped
位正在尋找空白行,並且在原始情況下是循環的終止特性。
那不是你的終止標記。 你不想在那里停下來。 所以不要。
當sys.stdin
到達輸入結束( EOF
)時,循環將自行完成。
if not stripped: break
刪除line.strip()
drop if not stripped: break
replace result = result + stripped
with result = result + line
,然后將其寫入文件以獲得一個簡單(雖然可能很昂貴)的cp
腳本。
如果您想對它們執行某些操作(取決於您的目標),可能有更有效的方法從標准輸入讀取所有行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.