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()**函数(返回一个列表,其中文件中的每一行都表示为列表项。要限制返回的行数,请使用hint参数。如果返回的字节总数超过指定数量,则不再返回行)获取给定输入文本文件的行列表。
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行并打印了它们。
结论
因此,从本文中,我们学习了如何打开文件并从中读取行,这可以用于执行诸如查找一行中的单词数量、一行的长度等操作,我们还学习了切片以简单的方式访问开头或结尾的元素。
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP