可能需要更多地解释您的数据关系。您想根据顺序编写条目,或者例如“abc”和“x”之间是否存在某种关系。无论如何,如果你想订购(不是正则表达式),这里是:
In [30]: cat /tmp/somefile
msgid 'abc'
msgstr ''
msgid 'def'
msgstr ''
msgid 'ghi'
msgstr ''
In [31]: content = ['x', 'y', 'z']
In [32]: with open('/tmp/somefile', 'r') as fh, open('/tmp/somenewfile', 'w') as fw:
...: for line in fh:
...: if 'msgstr' in line:
...: line = "msgstr '{}'\n".format(content.pop(0))
...: fw.write(line)
...:
...:
In [33]: cat /tmp/somenewfile
msgid 'abc'
msgstr 'x'
msgid 'def'
msgstr 'y'
msgid 'ghi'
msgstr 'z'
编辑,就地更改文件(确保保存文件的副本)
with open('/tmp/somefile', 'r+') as fw:
lines = fw.readlines()
fw.seek(0)
fw.truncate()
for line in lines:
if 'msgstr' in line:
line = "msgstr '{}'\n".format(content.pop(0))
fw.write(line)