【问题标题】:Replacing line in text file with python. How to?用python替换文本文件中的行。如何?
【发布时间】:2015-12-31 09:38:10
【问题描述】:

我在这里和那里寻找如何用新行替换文件中的多行,但我的代码只是在文件的最后添加一行。如何在合适的地方用新线替换旧线?

path = /path/to/file
new_line = ''
f = open(path,'r+b')
f_content = f.readlines()
line = f_content[63]
newline = line.replace(line, new_line)
f.write(newline)
f.close()

编辑: 路径 = /path/to/file path_new = 路径+".tmp" 新行 = "" 使用 open(path,'r') 作为 inf,open(path_new, 'w') 作为 outf: 对于 num,enumerate(inf) 中的行: 如果数字 == 64: newline = line.replace(line, new_line) outf.write(换行符) 别的: outf.write(行) new_file = os.rename(path_new, path)

【问题讨论】:

  • 尝试使用 f_content.seek(n) ,其中 n 是 line 的索引。 seek(0) 开始文件。
  • 新行和旧行长度一样吗?

标签: python


【解决方案1】:

大多数操作系统将文件视为二进制流,因此文件中没有一行。因此,您必须重写整个文件,并替换以下行:

new_line = ''
with open(path,'r') as inf, open(path_new, 'w') as outf:
    for num, line in enumerate(inf):
        if num == 64:
           outf.write(new_line)
        else:
           outf.write(line)
os.rename(path_new, path)

【讨论】:

  • 如果 path_new 和 path 是相同的代码只会创建空文件
  • 正确,因为它被覆盖了!你需要一个临时的第二个文件名,比如path_new = path + ".tmp"
【解决方案2】:

一般来说,你必须重写整个文件。

操作系统将文件公开为字节序列。当您打开文件时,这个序列有一个与之关联的所谓的文件指针。打开文件时,指针位于开头。您可以从此位置读取或写入字节,但不能插入或删除字节。在读取或写入 n 个字节后,文件指针将移动 n 个字节。

另外,Python 有一种读取整个文件并将内容拆分为行列表的方法。在这种情况下,这更方便。

# Read everything
with open('/path/to/file') as infile:
    data = infile.readlines()
# Replace
try:
    data[63] = 'this is the new text\n' # Do not forget the '\n'!
    with open('/path/to/file', 'w') as newfile:
        newfile.writelines(data)
except IndexError:
    print "Oops, there is no line 63!"

【讨论】:

  • 谢谢你,罗兰,终于成功了!还有一个小问题:用变量替换“这是新文本”应该是什么语法?
  • @AndriyKravchenko 就用data[63] = variable
猜你喜欢
  • 1970-01-01
  • 2013-05-13
  • 2011-02-26
  • 2020-03-28
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多