我正在制作一个脚本,它将终端中的文件作为输入。为了做到这一点,我像这样调用 myScript
:
$python myScript.py <fileInput.txt
脚本也很简单:
import fileinput
for line in fileinput.input():
if 'BLABLABLA' in line:
print(line, 'THAT IS THE LINE CONTAINING BLABLABLA from the file %s' %fileinput.filename())
但输出是:
Tweedledum said BLABLABLA! THAT IS THE LINE CONTAINING BLABLABLA from the <stdin>
我究竟做错了什么?
fileinput.filename()
如何工作?为什么输出 <stdin>
? 最佳答案
fileinput.input()
遍历 sys.argv[1:] 中列出的所有文件的行,如果列表为空 (source),则默认为 sys.stdin。<fileInput.txt
将 fileInput.txt
的内容发送到 stdin。文件名不会出现在 sys.argv
中,因为 input redirection 由您的 shell 处理。
如果文件名包含 <
字符(或任何其他“特殊”字符),您需要引用它:
$ python myScript.py '<fileInput.txt'
关于python - fileinput.filename() 如何工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33652769/