如何在python中同时读取和写入文本文件?

如何在python中同时读取和写入文本文件?,python,regex,mod-rewrite,text-files,Python,Regex,Mod Rewrite,Text Files,我试图打开一个文本文件,读取它,然后在使用正则表达式函数查找要编辑的行之后,修改我的文本文件。但是,在找到行并编辑它们之后,我无法将修改后的内容再次写入文本文件 remove_commas = re.compile("House") answer = {} global line1 with open("\DEMO_houses.txt", "r") as inp: for line in inp: if remove_commas.match(line):

我试图打开一个文本文件,读取它,然后在使用正则表达式函数查找要编辑的行之后,修改我的文本文件。但是,在找到行并编辑它们之后,我无法将修改后的内容再次写入文本文件

remove_commas = re.compile("House")
answer = {}

global line1

with open("\DEMO_houses.txt", "r") as inp:

    for line in inp:
        if remove_commas.match(line):

            line1 = line.replace(',', '')
            print line1

with open("DEMO_houses.txt", "w") as document1:
        document1.write(line1)
它只是删除了我的文本文件,只写修改后的第一行

文本文件如下所示:

Street : Blue, Red
House: Big, enough
Garden : green, not green
在新的文本文件中,我需要如下内容:

Street : Blue, Red
House: Big enough
Garden : green, not green

如果有人能帮助我,我将非常感激。谢谢,您可以尝试以下方法,目前的问题是您只存储和写入修改行的最后一个匹配项,而最好在内存中创建修改文件的副本,然后将其写出(见下文)


现在代码中发生的事情是,您首先以inp:块的形式读取
中的所有行(“\DEMO\u houses.txt”,“r”),然后以document1:
块的形式读取
中的所有行,您的代码只回写最后读取的行。由于写入模式
“w”
会擦除上一个文件,因此在代码完成执行后,只有原始文件的最后一行保留下来

您最好先将所有行读取到内存中,然后对这些行进行MDI,然后将它们写回同一个文件,如下所示:

import re

remove_commas = re.compile("House")

data = []
with open("DEMO_houses.txt", "r") as inp:  #Read phase
    data = inp.readlines()  #Reads all lines into data at the same time

for index, item in enumerate(data): #Modify phase, modification happens at once in memory
    if remove_commas.match(item):
        data[index] = item.replace(',', '')

with open("DEMO_houses.txt", "w") as document1: #write back phase
        document1.writelines(data)

如果文件可以无问题地存储在内存中,那么这是一种比一次读取和修改一行文件要好得多的方法,因为在内存中的修改要快得多,而辅助存储中的文件只会被修改一次。

如果我的文本文件是:Street:Blue,RedHouse:Big,Though Garden:green,不是温室:不是,在新的文本文件中,它只打印:House:Big enoughit打开和关闭文件两次如果使用两个open语句(如this@MuhsinFatih我对此表示怀疑,因为这些开放条件不会同时执行time@Maghilvannan想象一下以下内容:[多线程/多进程服务器启动并希望在每次请求时增加文本文件中的数字][进程1进入第一个
打开
块][进程1读取值
x
并退出块][进程2进入第一个
打开
块][进程2读取值
x
并退出块][进程1进入第二个
open
块并写入
x+1
并退出块][进程2进入第二个
open
块并写入
x+1
并退出块]。预期结果:文件包含
x+2
。实际结果:文件包含
x+1
@MuhsinFatih没有考虑多线程。我以为您的意思是在单个线程中打开和关闭文件。是的,如果我们使用多线程,将出现争用条件
import re

remove_commas = re.compile("House")

data = []
with open("DEMO_houses.txt", "r") as inp:  #Read phase
    data = inp.readlines()  #Reads all lines into data at the same time

for index, item in enumerate(data): #Modify phase, modification happens at once in memory
    if remove_commas.match(item):
        data[index] = item.replace(',', '')

with open("DEMO_houses.txt", "w") as document1: #write back phase
        document1.writelines(data)