我有两个文件 cities.txt 和 Detab.yml ,其中 cities.txt 包含:
Hohndorf;07937 Sobrance;45893 Stampfl;83546 Buskow;16816
和 Detab.yml 包含:
Hohndorf am See07937 : 50.611879, 12.135526 Grünbach von Beruf73072 : 48.69889, 9.84289 Buskow16816 : 52.86737, 12.81375 Krangen16816 : 52.985, 12.854444 Stampfl abern83546 : 48.17145, 12.32192
我需要用 cities.txt 文件中的城市替换 Detab.yml 文件中的行。因此输出应如下所示:
Hohndorf07937 : 50.611879, 12.135526 Grünbach73072 : 48.69889, 9.84289 Buskow16816 : 52.86737, 12.81375 Krangen16816 : 52.985, 12.854444 Stampfl83546 : 48.17145, 12.32192
我的脚本看起来像这样,但是它不起作用:
with open('cities.txt', 'r') as f:
with open('Detab.yml', 'r+') as detab:
for city_line in f:
fields = city_line.split(';')
col1 = fields[0]
col2 = fields[1]
newstr = col1 + col2
for Detab_line in detab:
line_split = Detab_line[0:Detab_line.find(':')]
if col1 in line_split and col2 in line_split:
with open('output.yml', 'r+') as output:
output.write(Detab_line.replace(line_split, newstr))