如何搜索和替换行(如果存在)或追加(如果不存在)-Python



我在查找和替换test.txt文件中的特定行时遇到问题,如果该行不存在,则追加到文件末尾。当我运行代码时,它所做的就是追加到文件中,不管行是否在那里。任何帮助都将不胜感激。这是我一直在排除故障的代码片段:

def savefile():
# First determine if there is anything inside the box
if len(entry.get()) != 0:
isthere = False
# Read through file line by line
with open(os.path.join(sys.path[0], "test.txt"), "r+") as pf:
lines = pf.readlines()
for x in lines:
word = for_entry.get()
# Determine if the user has that line saved already
if x.find(word) != -1:
# Replace the old line with the new one
data = []
data.append(pf.readlines())
data[0] = word + ": " + entry.get() + "n"
pf.writelines(data)
isthere = True
# No need to continue the loop
break
if isthere == False:
file1 = open(os.path.join(sys.path[0], "test.txt"), "a")
file1.write(for_entry.get() + ": " + entry.get() + "n")
file1.close()

我尝试了各种方法来搜索文件和替换行。然而,在我使用的其他方法中,我最接近于获得所需结果的是只替换一个单词。不过,那个方法破坏了我的附加代码。这个代码至少是稳定的,尽管不能正常工作。

我想明白了。对于任何可能偶然发现我问题的人。这是我得到的:

import os
import sys

def update_file():
if len(entry.get()) != 0:
found = False
with open(os.path.join(sys.path[0], "test.txt"), "r") as pf:
line = pf.readlines()
word = []
for item in line:
word.append(item.split(":"))
flatlist=[]
for sublist in word:
for element in sublist:
flatlist.append(element)
itvar = 0
for i in flatlist:
if i == for_entry.get():
flatlist[itvar + 1] = ": " + entry.get() + "n"
found = True
elif (itvar % 2) == 0:
flatlist[itvar + 1] = ": " + flatlist[itvar+1]
itvar = itvar + 1
if found == True:
file1 = open(os.path.join(sys.path[0], "test.txt"), "w")
flatlist = ''.join(flatlist)
file1.write(flatlist)
elif found == False:
file1 = open(os.path.join(sys.path[0], "test.txt"), "a")
file1.write(for_entry.get() + ": " + entry.get() + "n")
file1.close()

while语句将文件分解为一个列表。不幸的是,这个列表是嵌套的,所以我不得不将列表展开,并将其进一步分解为两个条目的单独字符串。然后,它确定第一个条目是否存在于细分列表中。如果它这样做了,那么它只将第二个条目替换为新生成的条目。如果没有,它会将新条目追加到列表的末尾。之后,它会重新构建列表,并将所有内容转换为列表上的一个字符串,然后用该字符串覆盖文件。有些模块可以做类似的事情,但我想看看我是否可以自己做。这是在具有以下语法的文本文件上测试的:

(条目1(:(条目2(

.get()从tkinter中构建的表单中提取条目。如果你觉得我的代码有用,可以随意使用。

最新更新