我想知道如何删除用户输入的单词,即" ant"从文本文件。文本文件中的每个单词已经分成不同的行:
ant
Cat
Elephant
...
这就是我所拥有的:
def words2delete():
with open('animals_file.txt') as file:
delete_word= input('enter an animal to delete from file')
答案 0 :(得分:1)
又一种方式
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)
答案 1 :(得分:0)
尝试类似:
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
答案 2 :(得分:0)
你可以尝试这样简单的事情
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()
答案 3 :(得分:0)
您可以先将文本文件转换为列表,然后执行此操作。文件中的每一行都是列表中的一个元素。它将从文本文件
中的所有位置删除指定的单词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))