如何使用 Python 将文本文件的奇数行复制到另一个文件

programmingpythonserver side programming

在本文中,我们将向您展示如何使用 Python 将文本文件的奇数行复制到另一个文本文件。

假设我们获取了一个名为 TextFile.txt 的文本文件,其中包含一些随机文本。我们需要将一个文本文件的所有奇数行复制到另一个文本文件中并打印它们。

TextFile.txt

Good Morning
This is the Tutorials Point sample File
Consisting of Specific
source codes in Python,Seaborn,Scala
Summary and Explanation
Welcome everyone
Learn with a joy

算法(步骤)

以下是执行所需任务要遵循的算法/步骤 -

  • 创建一个变量来存储文本文件的路径。

  • 使用 open() 函数(打开文件并返回文件对象)通过传递文件名和模式作为参数以只读模式打开文本文件(此处"r"代表只读模式)。

readFile = open(inputFile, "r")
  • 创建一个变量来存储输出文件路径,该路径仅包含给定输入文件中的奇数行。

  • 使用 open() 函数(打开文件并返回文件对象作为结果)通过传递文件名和模式作为参数以写入模式打开输出文件(此处"w"代表写入模式)。

  • 使用 readlines() 函数(返回一个列表,文件中的每一行都表示为一个列表项。要限制返回的行数,请使用提示参数。如果返回的字节总数超过指定的数量,则不再返回任何行)以获取给定输入文本文件的行列表。

file.readlines(hint)
  • 使用 for 循环遍历读取的文本文件的每一行,直到文件的长度。使用 len() 函数(len() 方法返回对象中的项目数)计算读取文件的长度。

  • 使用 if 条件语句,确定读取文件行的​​索引是否为奇数。

  • 如果条件为真,则使用 write() 函数(将指定的文本写入文件。提供的文本将根据文件模式和流位置插入)将读取的文件行写入输出文件。

  • 从给定的输入文件中打印奇数行。

  • 使用 close() 函数(用于关闭打开的文件)关闭写入文件(输出文件)。

  • 使用 close() 函数(用于关闭打开的文件)关闭读取文件(输入文件)文件)

示例

以下程序仅将文本文件的奇数行复制到另一个文本文件并打印结果奇数行 −

# input text file inputFile = "ExampleTextFile.txt" # Opening the given file in read-only mode. readFile = open(inputFile, "r") # output text file path outputFile = "PrintOddLines.txt" # Opening the output file in write mode. writeFile = open(outputFile, "w") # Read the above read file lines using readlines() ReadFileLines = readFile.readlines() # Traverse in each line of the read text file for excelLineIndex in range(0, len(ReadFileLines)): # Checking whether the line number i.e excelLineIndex is even or odd # Here modulus 2 i.e %2 gives 1 for odd number and 0 for even number if(excelLineIndex % 2 != 0): # If the index is odd, then x`write the read file line into the # output file writeFile.write(ReadFileLines[excelLineIndex]) # printing the odd line print(ReadFileLines[excelLineIndex]) # Closing the write file writeFile.close() # Closing the read file readFile.close()

输出

执行时,上述程序将生成以下输出 -

This is the Tutorials Point sample File
source codes in Python, Seaborn,Scala
Welcome everyone

我们给程序一个包含一些随机内容的文本文件,然后以读取模式打开它。然后使用 readlines() 函数检索文件中所有行的列表,并将其保存在变量中。我们遍历文件,直到达到整个行数,并检查行号是否为奇数。如果是奇数行,我们将其附加到新文件并打印出来。

结论

到目前为止,我们已经学习了如何打开文件、读取其行以及按索引遍历其行,这可用于获取信息,例如第 n 个索引行或 excel 表中第 n 行的值。此外,我们还讨论了如何按索引检索行的值并将该数据写入文件。


相关文章