2017-02-28 18 views
1

我有一個名爲「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」文件(第二讀,寫),並得到同樣的結果?

+0

如果文件小,閱讀這一切,並在內存中所做的一切。如果不是這樣,那麼就沒有辦法,因爲文件的存儲方式不會對它們進行插入。 –

+0

@ Am.rez謝謝,他們的大小將是動態的..有時很小,有時候很大......如果你在內存中編寫你的解決方案,感謝你的解答,謝謝 –

+0

對不起,沒有仔細閱讀代碼...輸入和輸出文件不同,因此您可以直接寫入輸出文件。 –

回答

0

打開文件讀取。然後替換字符。而不是寫入不同的文件,將其寫入Format.strings文件!

prefix = '"' 
suffix = '";' 
comment = '/* No comment test. */' 

f = codecs.open('Strings.txt',"r") 
t = codecs.open('Format.strings', 'w+') 

for line in f.readlines(): 
    t.writelines(comment + '\n') 
    line = line.replace(' = ', '\" = \"') 
    t.writelines('%s%s%s\n' % (prefix, line.rstrip('\n') , suffix)) 
    t.writelines("\n") 
f.close() 
t.close() 

產出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" = ""; 

/* No comment test. */ 
"Dial Plans" = "Disable Calls"; 

/* No comment test. */ 
"Details not available" = "Call Button"; 
+0

@Keertana,你測試了你的代碼嗎? –

+0

它的f.readlines()。我編輯了! –

+0

我在代碼中看到的問題是't = codecs.open('Format.strings','w +')中沒有聲明輸出編碼:它將使用ASCII輸入,但會失敗並顯示更高的字符。 @Benalison使用的編解碼器是 – Dario