from unidecode import *
reader = open("a.txt",'w')
def unite():
for line in reader:
line = unidecode(line)
print (line)
unite()
ここで、書き込みモードでは for ループが許可されていないというエラーが表示されます。ユニコードを使用して変換できるように、個々の行をそのように変更できますか?
from unidecode import *
reader = open("a.txt",'w')
def unite():
for line in reader:
line = unidecode(line)
print (line)
unite()
ここで、書き込みモードでは for ループが許可されていないというエラーが表示されます。ユニコードを使用して変換できるように、個々の行をそのように変更できますか?
すべてを記憶に留めることができます。
from unidecode import *
reader = open("a.txt",'w')
lines = reader.readlines()
def unite(lines):
for line in lines:
line = unidecode(line)
print (line)
unite()
一時ファイルを使用することもできます。
from unidecode import *
import os
reader = open('a.txt','r')
temp = open('~a.txt', 'w')
for line in reader():
line = unidecode(line)
temp.write(line)
reader.close()
temp.close()
os.remove('a.txt')
os.rename('~a.txt', 'a.txt')
追加モードで開くことができます:
def unite():
with open('somefile.txt','a+') as f:
for line in f:
f.write(unidecode(line))
print line
unite()
これにより、ファイルの最後に内容が書き込まれます。ファイルの先頭から内容を書き込むには、 mode を使用しますr+
。
例えば:
sample.txt
:
hello world
これを実行すると:
with open('sample.txt','a+') as f:
line = f.readline()
f.write('{} + again'.format(line.strip()))
ファイルには次のものが含まれます。
hello world
hello world again
実行する場合:
with open('sample.txt','r+') as f:
line = f.readline()
f.write('{} + once more'.format(line.strip()))
ファイルには次のものが含まれます。
hello world
hello world once more
hello world again
ファイルの内容を置き換えたい場合は、ファイルを読み取って行を保存し、ファイルを閉じて書き込みモードで開き、行を書き戻すことができます。
少し汚い秘密ですが、ファイルを「その場で」実際に変更できるアプリケーションはほとんどありません。ほとんどの場合、アプリケーションがファイルを変更しているように見えますが、内部では、編集されたファイルが一時的な場所に書き込まれ、元のファイルを置き換えるために移動されます。
考えてみれば、ファイルの途中に数バイトを挿入するときは、とにかくここからファイル全体を書き直さなければなりません。
ascii出力はunicode入力よりも小さくなる傾向があるため、おそらく次のようなものを実行できます(unixのみだと思います):
#!/usr/bin/env python
import os
from unidecode import unidecode
def unidecode_file(filename):
# open for write without truncating
fd = os.open(filename, os.O_WRONLY)
pos = 0 # keep track of file length
# open for read
with open(filename) as input:
for line in input:
ascii = unidecode(line.decode('utf-8'))
pos += len(ascii)
os.write(fd, ascii)
os.ftruncate(fd, pos) # truncate output
os.close(fd) # that is all, folks
if __name__ == '__main__':
unidecode_file('somefile.txt')
このスタントは安全ではなく、ファイルを編集するための標準的な方法ではありません (出力が入力よりも大きい場合、問題が発生することは間違いありません)。Drewによって提案された tempfile アプローチを使用しますが、ファイル名の一意性を確保してください (最も安全な方法は、一時ファイル用にランダムなファイル名を生成することです)。