文本文件中“用于循环”的子站点

2024-06-16 11:29:08 发布

您现在位置:Python中文网/ 问答频道 /正文

from unidecode import *
reader = open("a.txt",'w')
def unite():
    for line in reader:
        line = unidecode(line)
        print (line)
unite()

现在,我得到一个错误,说在写模式下不允许for循环。有没有其他方法,我可以修改每一行这样,它可以转换使用unidecode?你知道吗


Tags: 方法infromimporttxtfordef错误
3条回答

你可以把一切都记在记忆里。你知道吗

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()

这会把东西写到文件的末尾。要从文件开始写入内容,请使用模式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方法,但要确保文件名的唯一性(最安全的方法是为临时文件生成随机文件名)。你知道吗

相关问题 更多 >