使用 python 将文本文件中的一行替换为任何新行
Replace a line in a text file with any new line using python
假设我有一个文本文件 details.txt
details.txt
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 的行待定(例如:id=1=pending)与 (id=1=missing) 或 (id=1=found).
PS。请注意,我们只是将 pending 更改为 missing 或 found ,其余 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]=="pending\n": #pending\n 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=found) (id=1=foundng) ,因为 len(found ) 是 5 并且 len(pending) 是 7 ,所以在 pending 结束时额外的 2 个字符即 ng 不会被替换。
请告诉我该怎么做。
另外请告诉我,如果我想删除特定行,那么我该怎么做。
例如:
如果我想删除行 (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
请注意,该行与\n
一起被删除
任何帮助将不胜感激
不用 if 语句,使用正则表达式会有所帮助,
由于您要查找后跟单词 'pending'
的特定 ID,因此一个简单的正则表达式:"id=your_id=pending"
将起作用。
然后您可以使用re.sub
将整行替换为您想要的内容。这里id=your_id=missing/found"
Note : this answer is probably not the best one, since you re-write most of the lines, but for small files, works perfectly.
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
应该是
问题是,当你覆盖之前存在的文件时,它会替换文件中已经存在的字符,在这种情况下,碰巧“pending”的最后两个字母不需要将被覆盖。
要解决这个问题,您必须重写整个文件:
f = open("details.txt","r")
temp = f.readlines()
output_text = []
for line in temp:
word = line.split('=')
if word[1]=="1" and word[2]=="pending\n":
line = line.replace("pending\n", "found\n") # 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
假设我有一个文本文件 details.txt
details.txt
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 的行待定(例如:id=1=pending)与 (id=1=missing) 或 (id=1=found).
PS。请注意,我们只是将 pending 更改为 missing 或 found ,其余 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]=="pending\n": #pending\n 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=found) (id=1=foundng) ,因为 len(found ) 是 5 并且 len(pending) 是 7 ,所以在 pending 结束时额外的 2 个字符即 ng 不会被替换。
请告诉我该怎么做。
另外请告诉我,如果我想删除特定行,那么我该怎么做。
例如:
如果我想删除行 (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
请注意,该行与\n
一起被删除
任何帮助将不胜感激
不用 if 语句,使用正则表达式会有所帮助,
由于您要查找后跟单词 'pending'
的特定 ID,因此一个简单的正则表达式:"id=your_id=pending"
将起作用。
然后您可以使用re.sub
将整行替换为您想要的内容。这里id=your_id=missing/found"
Note : this answer is probably not the best one, since you re-write most of the lines, but for small files, works perfectly.
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
应该是
问题是,当你覆盖之前存在的文件时,它会替换文件中已经存在的字符,在这种情况下,碰巧“pending”的最后两个字母不需要将被覆盖。
要解决这个问题,您必须重写整个文件:
f = open("details.txt","r")
temp = f.readlines()
output_text = []
for line in temp:
word = line.split('=')
if word[1]=="1" and word[2]=="pending\n":
line = line.replace("pending\n", "found\n") # 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