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"代表只读模式)。
使用 open(inputFile, 'r') 作为文件数据:
使用 readlines() 函数(返回列表中的每一行都表示为一个列表项。要限制返回的行数,请使用提示参数。如果返回的总字节数超过指定的数量,则不会再返回任何行)以获取给定输入文本文件的行列表。
file.readlines(hint)
遍历行列表以使用切片检索文本文件的前 N 行(使用切片语法,您可以返回一系列字符。要返回字符串的一部分,请指定开始和结束索引,用冒号分隔)。这里linesList[:N]表示从开头到第N行的所有行(由于索引从0开始,所以不包括最后的第N行)。
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 行并打印它们。
结论
因此,从本文中,我们学习了如何打开文件并从中读取行,这可用于执行诸如查找一行中的单词数、一行的长度等操作,我们还学习了切片以简单的方式从开头或结尾访问元素。