Deleting a specific word from a file in python

2019-07-29 04:57发布

问题:

I am quite new to python and have just started importing text files. I have a text file which contains a list of words, I want to be able to enter a word and this word to be deleted from the text file. Can anyone explain how I can do this?

text_file=open('FILE.txt', 'r')
ListText = text_file.read().split(',')
DeletedWord=input('Enter the word you would like to delete:')
NewList=(ListText.remove(DeletedWord))

I have this so far which takes the file and imports it into a list, I can then delete a word from the new list but want to delete the word also from the text file.

回答1:

Here's what I would recommend since its fairly simple and I don't think you're concerned with performance.:

f = open("file.txt",'r')
lines = f.readlines()
f.close()

excludedWord = "whatever you want to get rid of"

newLines = []
for line in lines:
    newLines.append(' '.join([word for word in line.split() if word != excludedWord]))

f = open("file.txt", 'w')
for line in lines:
    f.write("{}\n".format(line))
f.close()

This allows for a line to have multiple words on it, but it will work just as well if there is only one word per line

In response to the updated question:

You cannot directly edit the file (or at least I dont know how), but must instead get all the contents in Python, edit them, and then re-write the file with the altered contents

Another thing to note, lst.remove(item) will throw out the first instance of item in lst, and only the first one. So the second instance of item will be safe from .remove(). This is why my solution uses a list comprehension to exclude all instances of excludedWord from the list. If you really want to use .remove() you can do something like this:

while excludedWord in lst:
    lst.remove(excludedWord)

But I would discourage this in favor for the equivalent list comprehension



回答2:

We can replace strings in files (some imports needed;)):

import os
import sys
import fileinput

for line in fileinput.input('file.txt', inplace=1):
    sys.stdout.write(line.replace('old_string', 'new_string'))

Find this (maybe) here: http://effbot.org/librarybook/fileinput.htm

If 'new_string' change to '', then this would be the same as to delete 'old_string'.