如何使用 Python 将文本文件中的奇数行复制到另一个文件
在本文中,我们将向您展示如何使用 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() 函数(返回一个列表,其中文件中的每一行都表示为列表项。要限制返回的行数,请使用 hint 参数。如果返回的字节总数超过指定数量,则不再返回行)获取给定输入文本文件的行列表。
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 行的值等信息。此外,我们讨论了如何通过索引检索行的值并将该数据写入文件。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP