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

2024-05-14 08:49:14 发布

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

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

ant
Cat
Elephant
...

这就是我所拥有的:

def words2delete():
   with open('animals_file.txt') as file:
       delete_word= input('enter an animal to delete from file')

Tags: 用户txtdefaswithopendelete单词
3条回答

另一种方式

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)

你可以试试这种简单的方法

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

尝试以下方法:

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

如果需要对同一个文件进行更改,最好的选择是通常将文件重命名为类似animals_file.txt.old(避免在崩溃中丢失信息)的名称并写入新文件。如果一切顺利完成,您可以删除.old

相关问题 更多 >

    热门问题