gpt4 book ai didi

python - 从文本文件中删除名称

转载 作者:行者123 更新时间:2023-11-28 22:32:26 24 4
gpt4 key购买 nike

我遇到的另一个问题是,我有这段代码可以从文本文件中删除名称。我不确定为什么,但有时它工作正常并且确实删除了名称,但通常情况下没有,有没有更好的方法可以 100% 地工作?我已经更改了我的文件路径和文件名,因为你们不需要它。

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()

最佳答案

with open(r"MyFilePath\MyFile.txt","r") as file:
participants=[]
for line in file:
participants.append(line)

leavingParticipant=input("Enter leaving participant: ")

with open(r"MyFilePath\MyFile.txt","w") as file:
for participant in participants:
if leavingParticipant != participant.strip():
file.write(participant)

您不需要在上下文管理器中手动关闭文件(with..as 语句)。与其尝试使用我们需要的信息周围的空白,不如将其删除以进行比较。

关于python - 从文本文件中删除名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40912443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com