![](/img/trans.png)
[英]How to replace the first specific special character in each line by not touching the rest of that word in each of the line of a text file in python
[英]Replace each line containing a specific word from the first file with the line from the second file
我有两个 txt 文件,第一个包含重复的单词“PACKAGES”,我想用文件 2 中的一行替换每个“PACKAGES”单词
文件 1 的示例:
NEW FUSTAT TOURS
City
USA
Address
napolean
PACKAGES
Test TOURS
City
UK
Address
napolean
PACKAGES
这是您可以做到的一种方法:
with open('file1.txt', encoding='utf-8') as f1:
with open('file2.txt', encoding='utf-8') as f2:
f2lines = iter(f2.readlines())
for f1line in f1:
if f1line.startswith('PACKAGES'):
print(next(f2lines), end='')
else:
print(f1line, end='')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.