Python不会写入文件

时间:2015-02-25 20:57:21

标签: python file io

替换文件中的行有问题。不确定更改是否未写入文件或数据行未被替换。 以下是我尝试这样做的方法:

filename = "filename.txt"
f = open(filename, "r+")

lines = [line1, line2, line3]

for line in lines:
    data = f.read()
    new_line = "some new line"
    data.replace(line, new_line)

f.write(data)
f.close()

问题出在哪里?

2 个答案:

答案 0 :(得分:2)

replace函数不会对对象本身进行更改,但会返回一个新字符串。所以你需要的是:

data = data.replace(line, new_line)

根据Roger的评论,您的代码应如下所示:

filename = "filename.txt"
f = open(filename, "r+")

lines = [line1, line2, line3]
data = f.read()

for line in lines:
    new_line = "some new line"
    data = data.replace(line, new_line)

f.write(data)
f.close()

希望它有所帮助。

答案 1 :(得分:0)

import fileinput 

for line in fileinput.input( filename , inplace = 1 ):
   print line.replace("SOMETHING", "SOMETHING ELSE" ), # catch for double line breaks

对于内联编辑文件很有用。