Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:打开文件,编辑一行,另存为同一文件_Python_Io - Fatal编程技术网

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

python:打开文件,编辑一行,另存为同一文件,python,io,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)): myNu

我想打开一个文件,搜索特定的单词,更改单词,然后再次保存文件。听起来很简单,但我就是不能让它工作。。。我知道我必须覆盖整个文件,但只更改这一个字

我的代码:

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 :)
如果我这样做,“新建”myfile文件只包含更改的行。但是我想要整份文件和修改过的行。。。有人能帮我吗

****编辑*****

我修好了!我刚把线圈转过来,现在它的工作原理是这样的:

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

当前代码有三个问题。首先,在开始循环之前创建
f2
文件句柄,否则将在每次迭代中覆盖该文件。第三,您正在
f2中写入未修改的行。写入(行)
。我猜你的意思是写(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()
使用传入任何要替换的内容:

import  fileinput
for line in fileinput.input("in.txt",inplace=True):
    print(line.replace("whatever","foo"),end="")
您似乎没有在循环中执行任何无法在循环外首先计算的特殊操作,因此请创建要替换单词的字符串,并将其传递给replace

inplace=True
表示原始文件已更改。如果要验证一切是否正常,请在第一次运行时删除
inplace=True
,您将实际看到替换的输出,而不是写入文件的行

如果要写入临时文件,可以使用带:

你可能遇到的一个问题是用替换来匹配子串,所以如果你知道单词总是在一个被空格包围的句子中间,那么你可以加上这个词,但是如果没有,你就需要拆分和检查每个单词。

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

你只需要在走的时候写出所有其他的行。正如我在评论中所说,我不知道您真正想用替换来做什么,但这里有一个稍微简化的版本,我们只是用“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)

您正在使用
'w'
模式截断整个文件,只写出一行
;你期望什么?好吧,如果你这样写的话,我不可能期望有什么不同。但这是唯一的解决方案来写一个文件,我发现。。。这就是我发布这个问题的原因。那我该怎么做呢?@Cheng OP想在适当的位置替换该行,不一定附加。@Cheng:但我不想将其添加到文档的末尾。行必须按顺序抵抗,只有这一个词必须改变…@straumle:你想对内部的
for
循环做什么,你只需要在第一次迭代中将“word”替换为“2”,然后就我所知不做任何其他事情?嗨,谢谢你的回答。我想在每次迭代中覆盖文件:),如果我这样做,它只会在文本文件的末尾添加一行。但那不是我想要的。我想替换现有文件中的单词,使它看起来完全相同,除了这一个单词…嗯。。。这也行不通。然后它就用这一行覆盖了整个文档…@straumle,发生这种情况的唯一方法是,如果要替换的单词是整个文件,则必须知道,在
FileInput
上设置
inplace
选项将临时接管脚本的当前
stdout
,这取决于您的使用情况。除非这只是一个简单的实用程序脚本,否则使用
open
函数读/写文件可能更有意义。这只会在
whatever
出现在行中时用
foo
替换
whatever
,如果行中没有
whatever
则原始行按原样写入。Hi Max.Hmm。。。。好的,但那也不行。它只是用新行替换整个文档。但我只想替换这一行,而文件的所有其他行必须保持不变……我已经测试过了,它似乎像我预期的那样工作。如果我创建了一个包含多行的文件,其中一些包含字符串“word”,那么在运行上述任一程序后,该文件仍然包含相同数量的行,只是所有出现的“word”都更改为“new”。
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)