我遇到的另一个问题是,我有一个从文本文件中删除名称的代码。我不太清楚为什么,但有时它能很好地去除这个名字,但通常情况下不会,有没有更好的方法可以百分之百地工作呢?我已经改变了我的文件路径和文件名,因为你们不需要。在
with open(r"MyFilePath\MyFile.txt","r") as file:
participants=[]
for line in file:
participants.append(line)
file.close()
leavingParticipant=input("Enter leaving participant: ")
file=open(r"MyFilePath\MyFile.txt","w")
for participant in participants:
if participant!=leavingParticipant+"\n":
file.write(participant)
file.close()
首先,您不需要读取行并手动将它们追加到列表中,因为每当您打开文件时,
open()
函数都会返回一个file对象,它是一个类似迭代器的对象,包含所有行。或者,如果您想缓存它们,可以使用readlines()
方法。在第二,当你关闭一个文件的cd3语句时,你不需要关闭它的文件。在
考虑到前面提到的注意事项,您可以选择使用临时文件对象来同时读取和修改文件。幸运的是,python为我们提供了
tempfile
模块,在本例中您可以使用NamedTemporaryFile
方法。并使用shutil.move()
将临时文件替换为当前文件。在让我们重新编写一些代码。第一个
file
是一个保留字,所以最好不要重载它。其次,由于您使用with
来打开文件,所以不需要使用.close()
。当with
子句结束时,它会自动执行此操作。您不需要迭代参与者列表。有几种方法可以处理从列表中删除项目。在这里使用.remove(item)
可能是最合适的。在您不需要手动关闭上下文管理器中的文件(
with..as
语句)。与其试着在我们需要的信息周围使用空白,不如将其删除以便进行比较。在相关问题 更多 >
编程相关推荐