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
相关问题 更多 >
编程相关推荐