如何在 Python 中读取 stdin 中的输入内容
本教程讨论了在 Python 中从 stdin
读取输入的方法。可以直接从控制台读取,也可以从控制台中指定的文件名读取。
在 Python 中使用 fileinput.input()
来读取 stdin
我们可以在 Python 中使用 fileinput
模块来读取 stdin
。fileinput.input()
读取命令行参数中指定的输入文件名的所有行。如果没有指定参数,它将读取提供的标准输入。
下面的例子说明了如何从指定的输入文件名中读取。
我们将使用下面的 sample.txt
。
Hello
Line1
Line2
下面是脚本 read.py
。
import fileinput
for line in fileinput.input():
print(line.rstrip())
我们这样执行它。
python read.py "sample.txt"
输出:
Hello
Line1
Line2
下面的例子说明了从标准输入中读取数据。
import fileinput
for line in fileinput.input():
print("Output:", line.rstrip())
执行和输出如下所示。
python read.py
Line 1
Output: Line 1
Line 2
Output: Line2
^Z
我们可以保存数据以便以后处理,如下所示:
import fileinput
data = []
for line in fileinput.input():
data.append(line.rstrip())
注意,我们使用了 line.rstrip()
. 就是删除后面的换行。
输入 y
会删除所有的变量。
在 Python 中使用 sys.stdin
来读取 stdin
另一种方法是使用 sys.stdin
来读取 Python 中的 stdin
。下面的例子说明了从 stdin
逐行读取数据。
import sys
for line in sys.stdin:
print("Output:", line.rstrip())
执行和输出如下所示。
python read.py
Line 1
Output: Line 1
Line 2
Output: Line2
^Z
我们也可以一次性从 stdin
中读取所有数据,而不必逐行读取。
下面的例子说明了这一点。
import sys
data = sys.stdin.readlines()
data = [line.rstrip() for line in data]
注意我们使用了 line.rstrip()
。这是为了删除尾部的换行符。
结论
我们讨论了 Python 中读取 stdin
输入的两种方法,fileinput.input()
和 sys.stdin
。fileinput.input()
可以从命令行参数中指定的文件名或标准输入中读取数据,而 sys.stdin
只能从标准输入中读取数据。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串