从文本fi中删除名称

2024-09-27 09:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到的另一个问题是,我有一个从文本文件中删除名称的代码。我不太清楚为什么,但有时它能很好地去除这个名字,但通常情况下不会,有没有更好的方法可以百分之百地工作呢?我已经改变了我的文件路径和文件名,因为你们不需要。在

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

Tags: 代码intxt名称forcloselineopen
3条回答

首先,您不需要读取行并手动将它们追加到列表中,因为每当您打开文件时,open()函数都会返回一个file对象,它是一个类似迭代器的对象,包含所有行。或者,如果您想缓存它们,可以使用readlines()方法。在

第二,当你关闭一个文件的cd3语句时,你不需要关闭它的文件。在

考虑到前面提到的注意事项,您可以选择使用临时文件对象来同时读取和修改文件。幸运的是,python为我们提供了tempfile模块,在本例中您可以使用NamedTemporaryFile方法。并使用shutil.move()将临时文件替换为当前文件。在

import tempfile
import shutil

leavingParticipant=input("Enter leaving participant: ")
filename = 'filename'
with open(filename, 'rb') as inp, tempfile.NamedTemporaryFile(mode='wb', delete=False) as out:
    for line if inp:
        if line != leavingParticipant:
            put.write(line)


shutil.move(out.name, filename)

让我们重新编写一些代码。第一个file是一个保留字,所以最好不要重载它。其次,由于您使用with来打开文件,所以不需要使用.close()。当with子句结束时,它会自动执行此操作。您不需要迭代参与者列表。有几种方法可以处理从列表中删除项目。在这里使用.remove(item)可能是最合适的。在

with open(r"MyFilePath\MyFile.txt","r") as fp:
    participants=[]
    for line in fp:
        participants.append(line.strip())  #remove the newline character

leavingParticipant = input("Enter leaving participant: ")

with open(r"MyFilePath\MyFile.txt","w") as fp2:
    if leavingParticipant in participants:
        participant.remove(leavingParticipant)
    file.write('\n'.join(participant))
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语句)。与其试着在我们需要的信息周围使用空白,不如将其删除以便进行比较。在

相关问题 更多 >

    热门问题