如何在python中从txt文档中删除单词

如何在python中从txt文档中删除单词,python,file,text,delete-file,delete-row,Python,File,Text,Delete File,Delete Row,我想知道如何从文本文件中删除用户输入的单词,即“ant”。文本文件中的每个单词都已分成不同的行: ant Cat Elephant ... 这就是我所拥有的: def words2delete(): with open('animals_file.txt') as file: delete_word= input('enter an animal to delete from file') 尝试以下方法: with open('animals_file.txt', '')

我想知道如何从文本文件中删除用户输入的单词,即“ant”。文本文件中的每个单词都已分成不同的行:

ant
Cat
Elephant
...
这就是我所拥有的:

def words2delete():
   with open('animals_file.txt') as file:
       delete_word= input('enter an animal to delete from file')
尝试以下方法:

with open('animals_file.txt', '') as fin:
   with open('cleaned_file.txt', 'w+') as fout:
       delete_word= input('enter an animal to delete from file')

       for line in fin:
           if line != delete_word:
               fout.write(line+'\n')

如果您需要更改同一个文件,最好的选择通常是将您的文件重命名为类似
anivers\u file.txt.old
(避免在崩溃时丢失信息)的文件,然后写入新文件。如果一切都成功完成,您可以删除
.old

您可以尝试这样简单的方法

file_read = open('animals_file.txt', 'r')
animals = file_read.readlines()
delete_animal = input('delete animal: ')
animals.remove(delete_animal)
file_write = open('animals_file.txt', 'w')
for animal in animals:
    file_write.write(animal)
file_write.close()
另一种方式

delete_word = input('enter an animal to delete from file') # use raw_input on python 2
with open('words.txt') as fin, open('words_cleaned.txt', 'wt') as fout:
    list(fout.write(line) for line in fin if line.rstrip() != delete_word)

您可以先将文本文件转换为列表来完成此操作。文件中的每一行都将是列表中的一个元素。它将从文本文件中的所有位置删除指定的单词

toremove='ant'
word=toremove+'\n' #add new line format with the word to be removed
infile= open('test.txt','r')
lines= infile.readlines() #converting all lines to listelements
infile.close()
# make new list, consisting of the words except the one to be removed
newlist=[i for i in lines if i!=word]  #list comprehension 
outfile= open('test.txt','w')
outfile.write("".join(newlist))
outfile.close
实现相同技术的另一种方法:

word='ant'
with open('test.txt', 'r') as infile:
    newlist= [i for i in infile.read().split() if i!=word]
with open('test.txt','w') as outfile:
    outfile.write("\n".join(newlist))

读取所有行,对于每行,删除输入字并重写它。文件中每行末尾的
\n
可能是重复的吗?瞧!只需将“\n”添加到正在写入的行即可。由于
\n
是从文件读取的行的一部分,因此比较不起作用。是否确定?AFAIK python读取每一行,但不带
\n
。无论如何,使用
行上的
.rstrip()
方法
最好的方法是自己尝试一下这个解决方案效果很好。另外,我使用的是
python2.7
,需要将
raw\uuu
添加到
input
函数中,以防这有助于解决OP。