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

Python “的子站点”;“用于循环”;在文本文件中,python,for-loop,filewriter,file-read,unidecoder,Python,For Loop,Filewriter,File Read,Unidecoder,现在,我得到一个错误,在写模式下不允许for循环。有没有其他方法,我可以像这样修改每一行,使用unidecode进行转换?您可以将其全部保存在内存中 from unidecode import * reader = open("a.txt",'w') def unite(): for line in reader: line = unidecode(line) print (line) unite() 您也可以使用临时文件 from unidecode

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

您可以将其全部保存在内存中

from unidecode import *
reader = open("a.txt",'w')
def unite():
    for line in reader:
        line = unidecode(line)
        print (line)
unite()
您也可以使用临时文件

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')
这会将内容写入文件的末尾。要从文件开始写入内容,请使用模式
r+

例如:

sample.txt

def unite():
    with open('somefile.txt','a+') as f:
        for line in f:
            f.write(unidecode(line))
            print line

unite()
运行此操作时:

hello world
该文件将具有:

with open('sample.txt','a+') as f:
    line = f.readline()
    f.write('{} + again'.format(line.strip()))
with open('sample.txt','r+') as f:
    line = f.readline()
    f.write('{} + once more'.format(line.strip()))
如果您运行:

hello world
hello world again
该文件将具有:

with open('sample.txt','a+') as f:
    line = f.readline()
    f.write('{} + again'.format(line.strip()))
with open('sample.txt','r+') as f:
    line = f.readline()
    f.write('{} + once more'.format(line.strip()))

如果你想替换文件的内容,那么你可以读取文件,保存行,关闭它,然后在写模式下打开它来写回行。

这是一个肮脏的秘密,但很少有应用程序能够真正“就地”更改文件。大多数情况下,应用程序似乎正在修改文件,但在后台,编辑的文件被写入临时位置,然后移到另一个位置以替换原始文件

如果你想一想,当你在文件中间插入几个字节时,无论如何,你必须从这一点重写整个文件。< /P> 由于ascii输出往往比unicode输入小,因此您可能可以实现类似的功能(我想只有unix):


这种特技不安全,也不是编辑文件的标准方式(如果输出大于输入,您肯定会遇到麻烦)。使用建议的tempfile方法,但要确保文件名的唯一性(最安全的方法是为临时文件生成一个随机文件名)。

读取所有行,修改,然后写回。好吧,你不能像那样在适当的位置修改行。我如何在读取时编辑文件?@madprogramer你不能同时读取和写入。考虑打开另一个文件进行编辑。可以使用较低级别的OS API同时读取和写入,但仅在内容大小相同的情况下才有用(并且通常Unicode文本比“uniCeadoD”ASCII)长。<代码>阅读器< /代码>就足够了-这取决于Python版本<代码>读入()将整个文件存储在内存中。这对于小文件来说很好,但对于大文件来说可能会耗尽所有内存。