使用python将文本文件中的一行替换为任何新行



假设我有一个文本文件,名为details.txt
details.ttxt

id=0=pending
id=1=pending
id=abc2=pending
id=x2=found
#cursor always points to the new line since I am appending n in the end of each line

现在我有一个python文件,比如update.py,我要做的是用(id=1=缺失(或(id=1=找到(替换具有挂起(例如:id=1=挂起(的特定id的行

PS。注意,我们只是将pending更改为missing或found,rest id=1=相同。例如,如果我们将details.txt中的id=1=pending替换为id=1=found,则应该如下所示:

id=0=pending
id=1=found
id=abc2=pending
id=x2=found
#cursor always points to the new line since I am appending n in the end of each line

这是我写的
update.py

f = open("details.txt","r+")
temp = f.readlines()
for line in temp:
word = line.split('=')#using = as a delimiter
if word[1]=="1" and word[2]=="pendingn":    #pendingn because while writing, we are appending n to each line
striped = line.strip()
new_line = striped.replace("pending","found")
new_content = new_line     #id=1=found
pos = f.tell()      #it will give the current position
if pos-len(line)-1>=0:    #checking whether we have any line or not
pos = pos-len(line)-1     #going to the start of a line and -1 to remove n
f.seek(pos)        #setting the pointer to the start of the line we want to replace , (start of 2nd line in this case)
f.write(new_content)         #writing the content
f.close()

我得到的输出

id=0=pending
id=1=foundng
id=abc2=pending
id=x2=found
#cursor always points to the new line since I am appending n in the end of each line

因此,我们得到的不是(id=1=founding(,而是(id=1=findingTR

请告诉我该怎么做
还请告诉我,如果我想删除特定的行,那么我该怎么做。
例如:
如果我想移除行(id=abc2=pending(,我应该怎么做。
输出应该是这样的:

id=0=pending
id=1=pending
id=x2=found
#cursor always points to the new line since I am appending n in the end of each line

请注意,该行已与

一起删除。如有任何帮助,我们将不胜感激

使用正则表达式将有助于

由于您要查找一个后面跟着单词'pending'的特定id,因此一个简单的regex:"id=your_id=pending"就可以了。

然后可以使用re.sub将整行替换为所需内容。此处为id=your_id=missing/found"

注意:这个答案可能不是最好的,因为你重写了大部分行,但对于小文件,效果很好。

import re
FILENAME = "textfile.txt"
def update_file(filename,id,word_to_add,lines_to_remove):

lines_to_remove = [s + "n" for s in lines_to_remove] 
#adding n to all lines you want to remove
pattern =re.compile("^id="+str(id)+"=pending")
new_lines=[]
with open(FILENAME,'r+') as  file:
for line in file:
if line not in lines_to_remove: # keeping only lines desired
new_lines.append(pattern.sub("id=1="+word_to_add,line))
with open(FILENAME,'w') as  file:
file.writelines(new_lines)

return 0

update_file(FILENAME,1,"missing",["id=abc2=pending"])
#Output
#id=0=pending
#id=1=missing

如果打印new_content而不是f.write(new-content)。可以看出,问题实际上不在替换函数中,单词被替换为

# f.write(new_content)
print(new_content)

输出:id=1=found,因为它应该是

问题是,当你覆盖预先存在的文件时,它会替换文件中已经存在的字符,在这种情况下,";挂起";不需要被覆盖。

要解决这个问题,你必须重写整个文件:

f = open("details.txt","r")
temp = f.readlines()
output_text = []
for line in temp:
word = line.split('=')
if word[1]=="1" and word[2]=="pendingn":
line = line.replace("pendingn", "foundn") # replace pending with found 
output_text.append(line)
f.close()
f = open("details.txt", "w")
f.write("".join(output_text))
f.close()

现在文件是:

id=0=pending
id=1=found
id=abc2=pending
id=x2=found

最新更新