这是Python吗文件.seek()常规正确吗?

2024-05-28 18:58:31 发布

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

这个程序在我看来还可以,但最后却把垃圾写进了文件里。lines_of_interest是文件中需要更改的一组行(896227L425200L640221L,等等)。if-else例程确定该行上发生的更改。这是我第一次使用seek(),但相信语法是正确的。有人能发现代码中的错误使其正常工作吗?在

outfile = open(OversightFile, 'r+')
for lines in lines_of_interest:
        for change_this in outfile:
            line = change_this.decode('utf8', 'replace')
            outfile.seek(lines)
            if replacevalue in line:
                line = line.replace(replacevalue, addValue)
                outfile.write(line.encode('utf8', 'replace'))
                break#Only check 1 line
            elif not addValue in line:
                #line.extend(('_w\t1\t'))
                line = line.replace("\t\n", addValue+"\n")
                outfile.write(line.encode('utf8', 'replace'))
                break#Only check 1 line
outfile.close()

Tags: 文件ofinforiflineseekutf8
2条回答

你们都在文件上循环多次,但在再次读取之前永远不要重置位置。在

在第一次迭代中,首先读取行,然后在文件中的其他地方查找,写入该位置,然后从for change_this in out_file:循环中break。在

接下来,for lines in lines_of_interest:循环的下一次迭代开始再次从outfile读取,但文件现在位于最后一个outfile.write()离开的点。这意味着你现在正在读你刚刚写的数据后面的任何东西。在

这可能不是你想做的。在

如果您想从相同的位置读取行,并将其写回相同的位置,则需要首先查找并使用.readline()而不是迭代来读取行。然后在写作前再次搜索:

outfile=打开(OversightFile,'r+')

for position in lines_of_interest:
    outfile.seek(position)
    line = outfile.readline().decode('utf8', 'replace')
    outfile.seek(position)
    if replacevalue in line:
        line = line.replace(replacevalue, addValue)
        outfile.write(line.encode('utf8'))
    elif not addValue in line:
        line = line.replace("\t\n", addValue+"\n")
        outfile.write(line.encode('utf8')

但是请注意,如果您写出的数据比原始行短或长,则文件大小将而不是调整!写入较长的行将覆盖下一行的第一个字符,较短的写入将在文件中保留旧行的尾随字符。在

您应该认为文件是不可更改的(除非您想附加到文件)。如果要更改文件中的现有行,请执行以下步骤:

  1. 从你的输入文件中读出每一行。数据.txt在
  2. 将每一行(包括更改的行)写入输出文件,例如new_文件.txt在
  3. 删除输入文件。在
  4. 将输出文件重命名为输入文件名。在

在步骤2)中,您不想处理的一个问题是,尝试使用一个不存在的文件名。tempfile模块将为您完成此操作。在

fileinput模块可用于透明地执行所有这些步骤:

#1.py
import fileinput as fi

f = fi.FileInput('data.txt', inplace=True)

for line in f:
    print "***" + line.rstrip()

f.close()

 output: 
$ cat data.txt
abc
def
ghi
$ python 1.py 
$ cat data.txt
***abc
***def
***ghi

fileinput模块打开您给它的文件名并重命名该文件。然后print语句被定向到用原始名称创建的空文件中。完成后,重命名的文件将被删除(或者您可以指定它应该保留)。在

相关问题 更多 >

    热门问题