小编str*_*mle的帖子

python:打开文件,编辑一行,将其另存为同一文件

我想打开一个文件,搜索一个特定的单词,更改单词并再次保存文件。听起来确实很简单-但我无法使其正常工作...我知道我必须覆盖整个文件,但只能更改一个字!

我的代码:

f = open('./myfile', 'r')
linelist = f.readlines()
f.close

for line in linelist:
    i =0;
    if 'word' in line:
        for number in arange(0,1,0.1)):
            myNumber = 2 - number
            myNumberasString = str(myNumber)

            myChangedLine = line.replace('word', myNumberasString)


            f2 = open('./myfile', 'w')
            f2.write(line)
            f2.close

            #here I have to do some stuff with these files so there is a reason
            #why everything is in this for loop. And I know that it will
            #overwrite the file every loop and that is good so. …
Run Code Online (Sandbox Code Playgroud)

python io

5
推荐指数
3
解决办法
1万
查看次数

标签 统计

io ×1

python ×1