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')
#!/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')
你可以把一切都记在记忆里。你知道吗
你也可以使用临时文件。你知道吗
您可以在附加模式下打开它:
这会把东西写到文件的末尾。要从文件开始写入内容,请使用模式
r+
。你知道吗例如:
sample.txt
:运行此操作时:
文件将具有:
如果您跑步:
文件将具有:
如果您想替换文件的内容,那么您可以读取文件,保存行,关闭它,然后以写模式打开它来写回行。你知道吗
这是一个肮脏的秘密,但很少有应用程序能够真正改变一个文件“原地”。大多数情况下,应用程序看起来是在修改文件,但在后台,编辑的文件被写入临时位置,然后移到原来的位置。你知道吗
如果你仔细想想,当你在文件中间插入几个字节时,无论如何,你必须从这一点重写整个文件。你知道吗
由于ascii输出往往比unicode输入小,所以您可能可以得到这样的结果(我想只有unix):
这种特技是不安全的,也不是编辑文件的标准方法(如果输出大于输入,您肯定会遇到麻烦)。使用Drew建议的tempfile方法,但要确保文件名的唯一性(最安全的方法是为临时文件生成随机文件名)。你知道吗
相关问题 更多 >
编程相关推荐