简体   繁体   English

如何用python中的file2中的行替换file1中的指定行

[英]How to replace specified lines from file1 with lines from file2 in python

I have two files... file1 and file2.我有两个文件...file1 和file2。 file1 is A LOT of text (no real structure) and file2 is made up of longitude points, each point is on a new line. file1 是很多文本(没有真正的结构),file2 由经度点组成,每个点都在一个新行上。

Eg (file2)例如(文件 2)

26.78883
25.09446
26.23765
etc.

So in file1 i have "$$$" throughout the file, not just once.所以在file1中,我在整个文件中都有“$$$”,而不仅仅是一次。 How can i replace each "$$$" with a line from file2?如何用 file2 中的一行替换每个“$$$”? The first line in file2 would replace the first "$$$" and then the second file2 line replaces the second "$$$" in file1 and so on... file2 中的第一行将替换第一个 "$$$",然后第二个 file2 行替换 file1 中的第二个 "$$$",依此类推...

I am a complete noob and have been struggling with this for a while.我是一个完整的菜鸟,并且已经为此苦苦挣扎了一段时间。 Any help is greatlly appreciated!非常感谢任何帮助!

You could try something like this:你可以尝试这样的事情:

#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)

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

相关问题 将N行从File1复制到File2,然后删除File1中的复制行 - Copy N lines from File1 to File2, then delete copied lines in File1 如何仅使用file1中的索引从file2获取值(行)? - How do I obtain values(lines) from file2 using only indices in file1? 如何打印文件 1 和文件 2 中的行,其中文件 1 中的第 9 列小于文件 2 中的第 4 列 - How can I print lines from file1 and file2 where columns 9 in file 1 is less than column 4 in file 2 测试file1中的行是否是file2中的行的子集 - Test if the lines in file1 are a subset of the lines in file2 如果文件1中存在Python,如何删除文件2中的所有字符串? - How to delete all strings in file2 if exist in file1 with Python? 如何在python中显示file1到file2的变量内容 - how to display content of variables of file1 to file2 in python 比较2个文件并删除file2中与file1中找到的值匹配的任何行 - Compare 2 files and remove any lines in file2 when they match values found in file1 在tkinter中从file1按下按钮时如何跳转运行/执行file2 - How jump run/execute file2 when a button is pressed from file1 in tkinter 从For循环替换文件中的行 - Replace lines in file from For Loop 如果file1的第一列与file2中的任何字符串匹配,则将其替换为file1的第二列 - If the first column of file1 matches any string in file2, then replace it with the second column of file1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM