【问题标题】:How to replace specified lines from file1 with lines from file2 in python如何在python中用file2中的行替换file1中的指定行
【发布时间】:2021-09-29 20:02:11
【问题描述】:

我有两个文件... file1 和 file2。 file1 是很多文本(没有真正的结构),file2 由经度点组成,每个点都在一个新行上。

例如(文件2)

26.78883
25.09446
26.23765
etc.

所以在 file1 中,我在整个文件中都有“$$$”,而不仅仅是一次。如何用 file2 中的一行替换每个“$$$”? file2 中的第一行将替换第一个“$$$”,然后第二个 file2 行替换 file1 中的第二个“$$$”,依此类推...

我是一个完全的菜鸟,并且已经为此苦苦挣扎了一段时间。非常感谢任何帮助!

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以试试这样的:

    #read the first file to a string
    with open("file1.txt") as f:
        text = f.read()
    
    #read the second file to a list
    with open("file2.txt") as f:
        longitudes = f.read().split("\n")
    
    #replace each '$$$' with values from longitudes
    while len(longitudes)>0 or "$$$" in text:
        text = text.replace("$$$", longitudes.pop(0), 1)
       
    #write to a new file
    with open("output.txt", "w") as f:
        f.write(text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多