【发布时间】: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