简体   繁体   English

Python不在文件中写入

[英]Python doesn't write in file

Have problem with replacing lines in file. 在替换文件中的行时遇到问题。 Not sure if changes weren't written in file or data lines weren't replaced. 不知道是否未将更改写入文件或未替换数据行。 Here is how I tried to do this: 这是我尝试执行的操作:

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()

Where could the problem be? 问题可能在哪里?

The replace function doesn't make changes in the object itself, but it returns a new string. replace函数不会对对象本身进行更改,但会返回一个新字符串。 So what you need is: 因此,您需要的是:

data = data.replace(line, new_line)

And taking Roger's comment, your code should look like this: 考虑到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()

Hope it helps. 希望能帮助到你。

import fileinput 

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

useful for editing files inline. 用于内联编辑文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM