[英]How can i delete words from a txt document in python
我想知道如何從文本文件中刪除用戶輸入的單詞,即“ ant”。 文本文件中的每個單詞已經分為不同的行:
ant
Cat
Elephant
...
這就是我所擁有的:
def words2delete():
with open('animals_file.txt') as file:
delete_word= input('enter an animal to delete from file')
另一種方式
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)
嘗試類似:
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
您可以嘗試這樣的簡單操作
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()
您可以通過先將文本文件轉換為列表來完成此操作。 文件中的每一行都是列表中的一個元素。 它將從文本文件中的所有位置刪除指定的單詞
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.