【问题标题】:How to read line in text file and replace the whole line in Python?如何读取文本文件中的行并替换 Python 中的整行?
【发布时间】:2020-08-09 21:58:55
【问题描述】:

如果有一行以“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

【问题讨论】:

  • 听起来你有一些代码不能完全满足你的要求。你应该发一个minimal reproducible example。
  • 也许尝试遍历您的文件并将不等于“truck_placement”的行写入单独的文件或您的文件,因为它只会覆盖它。你想让我教你怎么做吗?
  • 包含一些代码,以便我们知道在哪里更正?
  • 我已将代码包含在问题中
  • 你能提供预期的输出吗?特别是您要覆盖的行?因为你的代码工作得很好。碰巧你把truck_placement: 放回原位,只在cordget后面加上newdata = filedata.replace("truck_placement: " , "truck_placement: " + cordget)

标签: python python-3.x tkinter replace


【解决方案1】:

最好的办法是将所有不带“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()

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-24
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多