要逐行修改txt文件,你可以使用以下步骤:

  1. 打开txt文件并读取内容。可以使用open()函数打开文件,并使用readlines()方法读取每一行的内容。将内容保存到一个列表中。
with open("file.txt", "r") as file:
    lines = file.readlines()
  1. 修改内容。对于每一行的内容,你可以使用字符串的一些方法来进行修改。例如,你可以使用replace()方法替换特定的字符串,或者使用split()方法拆分字符串并进行相应的修改。修改后的内容可以保存到一个新的列表中。
new_lines = []
for line in lines:
    # 修改内容
    modified_line = line.replace("old", "new")
    new_lines.append(modified_line)
  1. 将修改后的内容写入文件。可以使用open()函数以写入模式打开文件,并使用writelines()方法将修改后的内容写入文件。
with open("file.txt", "w") as file:
    file.writelines(new_lines)

完整的代码示例:

with open("file.txt", "r") as file:
    lines = file.readlines()

new_lines = []
for line in lines:
    modified_line = line.replace("old", "new")
    new_lines.append(modified_line)

with open("file.txt", "w") as file:
    file.writelines(new_lines)

请注意,这个示例假设你的txt文件较小,可以一次性读取到内存中进行修改。如果你的文件非常大,可能需要考虑逐行读取和写入文件,以避免占用过多的内存

python 逐行修改txt文件

原文地址: https://www.cveoy.top/t/topic/iOVW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录