带有 txt 文件和 input() 函数的 python 标准输入

标签 python input stdin

我有一个包含以下内容的 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/

相关文章:

python - 为什么 < 不能从命令行(简单的 Python 代码)读取文件?

javascript - 用于输入数字和逗号的正则表达式

java - 在java中的所有程序上使用一个字符串?

java - java程序执行时如何更改音频输入设备?

控制台 I/O : printf & scanf not occurring in expected order

python - MapReduce Python,似乎无法将条件传递到文本文件

python - Pandas ,将日期时间格式 mm/dd/yyyy 转换为 dd/mm/yyyy

python - 如何在DigitalOcean App平台中禁用CORS策略并允许从任何地址访问?

perl - 等待远程数据时读取STDIN;下载远程数据时终止

c - Ctrl-D(Unix)和Ctrl-Z(Windows)的不同行为