如何在 Python 中删除文本文件中的特定行?
在本文中,我们将向您展示如何使用 Python 从文本文件中删除特定行。
假设我们获取了一个名为 TextFile.txt 的文本文件,其中包含一些随机文本。我们将从文本文件中删除特定行(例如第 2 行)
TextFile.txt
Good Morning This is Tutorials Point sample File Consisting of Specific source codes in Python,Seaborn,Scala Summary and Explanation Welcome everyone Learn with a joy
算法
以下是执行所需任务需要遵循的算法/步骤 -
创建一个变量来存储文本文件的路径。
使用 open() 函数(打开文件并返回文件对象作为结果)通过传递文件名和模式作为参数以只读模式打开文本文件(此处 "r" 表示只读模式)。
使用 open(inputFile, 'r') 作为文件数据:
使用 readlines() 函数(返回一个列表,文件中的每一行都表示为一个列表项。要限制返回的行数,请使用提示参数。如果返回的总字节数超过指定的数量,则不会再返回任何行)来获取给定输入文本文件的行列表。
file.readlines(hint)
创建一个变量(保存行号)并将其值初始化为 1。
使用 open() 函数(打开文件并返回文件对象作为结果)以写入模式打开给定的文本文件,方法是将文件名和模式作为参数传递给它(此处 "w" 代表写入模式)。
with open(inputFile, 'w') as filedata:
使用 for 循环遍历文件的每一行。
使用input() 函数(input() 函数从输入(来自用户)读取一行,通过消除尾随换行符将其转换为字符串,然后返回它。当遇到 EOF 时,会抛出 EOFError 异常)并使用 int() 函数将其转换为整数(转换为整数)。
使用 if 条件语句,确定行索引(行号)是否不等于给定的删除行号。
如果条件为真,则使用 write() 函数(将指定的文本写入文件。提供的文本将根据文件模式和流位置插入)将相应的行写入文件。
将行索引(行号)的值增加 1。
如果成功删除了给定的特定行,则打印一些随机文本。
使用 open() 函数在读取模式下再次打开输入文件,以在删除给定的特定行后打印文件内容行。
使用 for 循环遍历文件的每一行。
打印文本文件的每一行。
使用 close() 函数关闭输入文件(用于关闭打开的文件)。
示例
以下程序从文本文件中删除给定行,并在删除该行后打印结果文件内容 −
# input text file inputFile = "TextFile.txt" # Opening the given file in read-only mode. with open(inputFile, 'r') as filedata: # Read the file lines using readlines() inputFilelines = filedata.readlines() # storing the current line number in a variable lineindex = 1 # Enter the line number to be deleted deleteLine = int(input("Enter the line number to be deleted = ")) # Opening the given file in write mode. with open(inputFile, 'w') as filedata: # Traverse in each line of the file for textline in inputFilelines: # Checking whether the line index(line number) is # not equal to a given delete line number if lineindex != deleteLine: # If it is true, then write that corresponding line into file filedata.write(textline) # Increase the value of line index(line number) value by 1 lineindex += 1 # Print some random text if the given particular line is deleted successfully print("Line",deleteLine,'is deleted successfully\n') # Printing the file content after deleting the specific line print("File Content After Deletion :") # Reading the file again in read mode givenFile = open(inputFile,"r") # Traversing the file line by line for line in givenFile: # printing each line print(line) # Closing the input file filedata.close()
输出
执行时,上述程序将生成以下输出 -
Enter the line number to be deleted = 2 Line 2 is deleted successfully File Content After Deletion : Good Morning Consisting of Specific source codes in Python,Seaborn,Scala Summary and Explanation Welcome everyone Learn with a joy
我们给程序一个包含一些随机内容的文本文件,然后以读取模式打开它。我们创建了一个变量来存储当前行号,并将其初始化为起始行号 1。我们遍历文件直到到达末尾,然后检查用户输入的数字是否等于要删除的行号。如果为假,我们不需要删除或移除该行,因此我们将其写入文件。我们不会删除指定的行,而是将剩余的行添加到文件中,因此删除的行不会出现在结果文件中。对于每一行,行号的值都会增加一。
在本文中,我们了解了如何从文本文件中删除特定行并在同一篇文章中保存剩余的行。除此之外,我们还了解了如何从头到尾遍历整个文本文件,以及如何读取和写入数据到文本文件中。