2017-02-28 14 views
1

私は次の形式を含む「Strings.txt」という名前のファイルパイソン - 読むと新しい書き込みに文字を追加し

text = text 

Strings.txtの小さなサンプルがあります

Incoming calls = See the Preferences 
Incoming message from %@ = Incoming message from %@ 
Enter Your Password = 

IをこのファイルをPythonで読み込み、いくつかの文字/文字列を挿入して "Format.strings"のような他のファイルに書きたい。

出力は

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」ファイル(第2読み出しと書き込み)を使用して回避し、取得する方法があります:ここで

/* No comment test. */ 
"Incoming calls" = "See the Preferences"; 

/* No comment test. */ 
"Incoming message from %@" = "Incoming message from %@"; 

/* No comment test. */ 
"Enter Your Password" = ""; 
は私のPythonコードのですか?

+0

ファイルが小さい場合には、それのすべてを読んで、メモリに全力を尽くします。そうでない場合、ファイルは挿入されない方法で格納されるため、方法はありません。 –

+0

@ Am.rezおかげで、彼らのサイズは動的になることがあります。時には小さくて時には大きい..あなたがメモリ内のすべてを行うことであなたの解決策を書くなら、ありがとう –

+0

申し訳ありません、慎重にコードを読んでいない...入力と出力ファイルが異なるため、出力ファイルに直接書き込むことができます。 –

答えて

0

読み込んだファイルを開きます。次に、文字を置き換えます。別のファイルに書き込む代わりに、Format.stringsファイルに書き込んでください!! 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() 

出力:

/* 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入力では動作しますが、 – Dario

関連する問題