繁体   English   中英

如何读取文本文件中的行并替换 Python 中的整行?

[英]How to read line in text file and replace the whole line in Python?

如果有一行以“truck_placement”开头,我想替换文本文档中的一整行

当它包含“truck_placement”时,我可以删除整行然后编写新文本吗?

我试过了,但它只插入新文本,并没有替换整行。

那是当前的代码:

cordget = coordinatesentry.get()
    fin = open(save_file,"r")
    filedata = fin.read()
    fin.close

    newdata = filedata.replace("truck_placement: " , "truck_placement: " + cordget)

    fin = open(save_file, "w")
    fin.write(newdata)
    fin.close

您最好的选择是将 append 所有没有“truck_placement”的行放到一个新文件中。 这可以通过以下代码完成:

original = open("truck.txt","r")
new = open("new_truck.txt","a")

for line in original:
    if "truck_placement" not in line:
        new.write(line)

original.close()
new.close()

您可以将整个文件读入一个字符串并使用正则表达式替换该行:

import re

cordget = "(value, one) (value, two)"
save_file = "sample.txt"

with open(save_file, "r") as f:
    data = f.read()

# Catch the line from "truck_placement: " until the newline character ('\n')
# and replace it with the second argument, where '\1' the catched group 
# "truck_placement: " is.
data = re.sub(r'(truck_placement: ).*\n', r'\1%s\n' % cordget, data)

with open(save_file, "w") as f:
    f.writelines(data)

或者您可以将文件作为所有行的列表读取并覆盖特定行:

cordget = "(value, one) (value, two)"
save_file = "sample.txt"

with open(save_file, "r") as f:
    data = f.readlines()

for index, line in enumerate(data):
    if "truck_placement" in line:
        data[index] = f"truck_placement: {cordget}\n"

with open(save_file, "w") as f:
    f.writelines(data)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM