[英]Reading input file to Python script, using CMD
我有以下問題。 我想從文件(例如 example.txt)讀取輸入到我的 Python 腳本(例如 script.py)。 現在,我已經實現了以下代碼行:
import sys
with open(sys.argv[1], 'r') as f:
contents = f.read()
而且,當我想讀取這個腳本的文件時,我只需要在 CMD 中鍵入以下行:
python script.py example.txt
當然,它可以正常工作。 文件 example.txt 由 script.py 讀取,可以通過在 script.py 中添加簡單的 print(contents) 行來檢查。
問題是,我必須像這樣在 CMD 中運行此代碼:
script.py < example.txt
所以,問題是,我怎樣才能做到這一點? 我想,這取決於操作系統。 在我的 Windows 10 上,出現錯誤:
Traceback (most recent call last):
File "script.py", line 2, in <module>
with open(sys.argv[1], 'r') as f:
IndexError: list index out of range
我不是在尋求解決方案(但這會很好),但我只是想知道我應該在哪里尋找解決方案。
script.py < example.txt
將文件內容發送到可以通過sys.stdin
訪問的標准輸入。 以下作品:
import sys
# First try supporting commands formatted like: script.py example.txt
if len(sys.argv) > 1:
with open(sys.argv[1]) as f:
contents = f.read()
# Now try supporting: script.py < example.txt
elif sys.stdin:
contents = ''.join(sys.stdin)
# If both methods failed, throw a user friendly error
else:
raise Exception('Please supply a file')
print(contents)
但是在好舊的 Python 時尚中,有一個內置庫可以讓我們的生活變得非常輕松。 該庫是fileinput ,它將自動支持您提到的兩種讀取輸入的方法:
import fileinput
contents = fileinput.input()
print( ''.join(contents) )
無論您是否執行script.py example.txt
或script.py < example.txt
或cat example.txt | script.py
這都有效 cat example.txt | script.py
你甚至可以做script.py example1.txt example2.txt example3.txt
你會收到不同文件組合在一起的文件內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.