我有一个包含以下内容的 input.txt 文件。
3
4 5
我想通过在命令行中使用以下命令将其用作标准输入。
python a.py < input.txt
在 a.py 脚本中,我尝试使用 input()
函数逐行读取输入。我知道有更好的方法来读取标准输入,但我需要使用 input()
函数。
一种幼稚的方法
line1 = input()
line2 = input()
没用。我收到以下错误消息。
File "<string>", line 1
4 5
^
SyntaxError: unexpected EOF while parsing
最佳答案
这样就可以了,有效:
read = input()
print(read)
但你只读了一行。
来自 input()文档:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
这意味着如果文件不以空行结尾,或者相同的情况,文件的最后一个非空行不以行结束
字符结尾,您将得到exceptions.SyntaxError
并且最后一行将不会被读取。
关于带有 txt 文件和 input() 函数的 python 标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45911367/