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

时间:2015-05-11 14:12:42

标签: python io

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

我的代码:

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. I want that :)

如果我这样做,'new'myfile文件只包含更改的行。但是我希望整个文件都有更改的行......任何人都可以帮助我吗?

**** ***** EDIT

我修好了!我只是转动了循环,现在它完全像这样:

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

i =0;
for number in arange(0,1,0.1):
    fw=open('mynewfile', 'w')

    myNumber = 2 - number
    myNumberasString = str(myNumber)
    for line in text:

        if 'word' in line:
            line = line.replace('word', myNumberasString)

        fw.write(line)
    fw.close()
    #do my stuff here where I need all these input files

3 个答案:

答案 0 :(得分:3)

您只需要随时写出所有其他行。正如我在评论中所说,我不知道你真正试图用你的替换做什么,但这里是一个略微简化的版本,我们只是用“new”替换所有出现的'word':

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

# Re-open file here
f2 = open('./myfile', 'w')
for line in linelist:
    line = line.replace('word', 'new')
    f2.write(line)
f2.close()

或使用上下文:

with open('./myfile', 'r') as f:
    lines = f.readlines()

with open('./myfile', 'w') as f:
    for line in lines:
        line = line.replace('word', 'new')
        f.write(line)

答案 1 :(得分:2)

使用fileinput传递您想要替换的内容:

import  fileinput
for line in fileinput.input("in.txt",inplace=True):
    print(line.replace("whatever","foo"),end="")

你似乎没有在你的循环中做任何特殊的事情,而这些事情在循环之外无法首先计算出来,所以创建你要替换单词的字符串并将其传递给替换。

inplace=True表示原始文件已更改。如果你想验证一切看起来没问题,那么在第一次运行时删除inplace=True,你实际上会看到替换的输出,而不是写入文件的行。

如果您要写入临时文件,可以NamedTemporaryFile使用shutil.move

from tempfile import NamedTemporaryFile
from shutil import move

with open("in.txt") as f, NamedTemporaryFile(dir=".",delete=False) as out:
    for line in f:
        out.write(line.replace("whatever","foo"))

move("in.txt",out.name)

你可能遇到的一个问题是匹配带有替换的子串,所以如果你知道这个词总是跟在一个被空格包围的句子中间,你可以添加它,但如果不是,你需要拆分并检查每个单词。

from tempfile import NamedTemporaryFile
from shutil import move
from string import punctuation
with open("in.txt") as f, NamedTemporaryFile(dir=".",delete=False) as out:
    for line in f:
        out.write(" ".join(word if word.strip(punctuation) != "whatever" else "foo" 
                 for word in line.split()))

答案 2 :(得分:1)

您当前的代码有三个问题。首先,在开始循环之前创建f2文件句柄,否则您将在每次迭代中覆盖该文件。第三,您正在f2.write(line)中编写未修改的行。我想你的意思是f2.write(myChangedLine)?第三,您应该添加一个else语句,将未修改的行写入文件。所以:

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

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.write(myChangedLine)
    else:
        f2.write(line)

f2.close()