Python 读取文件的前N行
在本文中,我们将展示如何使用Python读取和打印给定N值的文本文件的前N行。
假设我们有一个名为 ExampleTextFile.txt 的文本文件,其中包含一些随机文本。我们将返回给定N值的文本文件的前 N 行。
ExampleTextFile.txt
Good Morning Tutorials Point
This is Tutorials Point sample File
Consisting of Specific
abbreviated
source codes in Python Seaborn Scala
Imagination
Summary and Explanation
Welcome user
Learn with a joy
步骤
以下是执行所需任务的算法/步骤:
- 创建一个变量来保存文本文件的路径。
-
输入用于打印文件的前N行的N值(静态/动态)。
-
使用 open() 函数(打开文件并返回文件对象)来以只读模式打开文本文件,其中文件名和模式作为参数传递给它(这里“ r ”表示只读模式)。
with open(inputFile, 'r') as filedata:
- 使用 readlines() 函数(返回一个列表,其中每行文件都表示为一个列表项。要限制返回的行数,请使用提示参数。如果返回的字节数超过指定的数量,则不返回更多行)来获取给定输入文本文件的行列表。
file.readlines(hint)
- 遍历行列表以使用 切片 从文本文件中检索前N行。 (使用切片语法,您可以返回一系列字符。要返回字符串的一部分,请指定起始和结束索引,用冒号分隔)。这里的linesList[:N]表示从起始位置开始的所有行直到第N行(不包括第N个行,因为索引从0开始)。
for textline in (linesList[:N]):
-
按行打印文件的前N行。
-
使用 close() 函数关闭输入文件(用于关闭打开的文件)。
示例
下面的程序根据给定的 N 值,打印文本文件的前N行 –
# input text file
inputFile = "ExampleTextFile.txt"
# Enter N value
N = int(input("Enter N value: "))
# Opening the given file in read-only mode
with open(inputFile, 'r') as filedata:
# Read the file lines using readlines()
linesList= filedata.readlines()
print("The following are the first",N,"lines of a text file:")
# Traverse in the list of lines to retrieve the first N lines of a file
for textline in (linesList[:N]):
# Printing the first N lines of the file line by line.
print(textline, end ='')
# Closing the input file
filedata.close()
输出
执行上述程序后将生成以下输出 –
Enter N value: 4 The following are the first 4 lines of a text file:
Good Morning Tutorials Point
This is Tutorials Point sample File
Consisting of Specific
abbreviated
我们从用户那里获取了N的值(动态输入),然后给我们的程序一个包含一些随机内容的文本文件,然后以读取模式打开它。然后使用readlines()函数检索文件中所有行的列表。我们使用for循环和切片遍历了文件的前N行,并打印出来。
结论
所以,通过这篇文章,我们学习了如何打开文件并从中读取行,这可以用于执行诸如找到一行中的单词数量、一行的长度等操作,我们还学习了使用切片从开始或结束方向简单地访问元素。