擅长:python、mysql、java
<p>尝试以下方法:</p>
<pre><code>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')
</code></pre>
<p>如果需要对同一个文件进行更改,最好的选择是通常将文件重命名为类似<code>animals_file.txt.old</code>(避免在崩溃中丢失信息)的名称并写入新文件。如果一切顺利完成,您可以删除<code>.old</code></p>