我有一個名爲「Strings.txt」文件,該文件包含以下格式Python的 - 閱讀並追加字符到新的寫
text = text
Strings.txt的小樣本:
Incoming calls = See the Preferences
Incoming message from %@ = Incoming message from %@
Enter Your Password =
我想要在Python中讀取該文件,插入一些字符/字符串並將其寫入其他文件,如「Format.strings」
輸出將是:
/* No comment test. */
"Incoming calls" = "See the Preferences";
/* No comment test. */
"Incoming message from %@" = "Incoming message from %@";
/* No comment test. */
"Enter Your Password" = "";
這裏是我的Python代碼:
prefix = '"'
suffix = '";'
comment = '/* No comment test. */'
f = codecs.open('Strings.txt', encoding="utf-16")
o = codecs.open('temp.strings', 'w')
for line in f:
o.write(line.replace(' = ', '\" = \"'))
f.close()
o.close()
h = codecs.open('temp.strings', 'r')
t = codecs.open('Format.strings', 'w')
for l in h:
t.write(comment + '\n')
t.write('%s%s%s\n' % (prefix, l.rstrip('\n') , suffix))
t.write("\n");
t.close()
h.close()
有沒有辦法避免使用「temp.strings」文件(第二讀,寫),並得到同樣的結果?
如果文件小,閱讀這一切,並在內存中所做的一切。如果不是這樣,那麼就沒有辦法,因爲文件的存儲方式不會對它們進行插入。 –
@ Am.rez謝謝,他們的大小將是動態的..有時很小,有時候很大......如果你在內存中編寫你的解決方案,感謝你的解答,謝謝 –
對不起,沒有仔細閱讀代碼...輸入和輸出文件不同,因此您可以直接寫入輸出文件。 –