0

I am currently creating a program that allows a user to either add or remove any word to a word list that is in a txt file however, i am having issues removing certain words that the user has requested from said text file. Here is my code(disregard the other parts):

from test_words import word_list
test_list=open('test_words.txt')
test_list=test_list.read().splitlines()

def changewords():
    morewords=input('Would you like to change the word list?(Y/N)\n').upper()
    if morewords=='Y':
        which=input('Add, Delete, Clear or Reset?(A/D/C,R)\n').upper()
        if which=='A':
            add=input('What word would you like to add?\n')
            file=open('test_words.txt','a')
            file.write('\n')
            file.write(add)
            file.close()
            changewords()
        elif which=='D':
            remove=input('what word would you like to remove?\n')
            ???????
            file.close()
            changewords()
        elif which=='C':
            file=open('test_words.txt','w')
            file.write('')
            file.close()
            changewords()
        elif which=='R':
            file=open('test_words.txt','w')
            file.write('\n'.join(word_list))
            file.close()
            changewords()
        else:
            print('Incorrect input')
            changewords()
changewords()

Thanks for any help

Qu1ppy
  • 1
  • 1

1 Answers1

0

I'm assuming you don't want to modify test_list as this is the original contents of the file that needs to remain the same in case the user requests to 'reset' the file.

To remove the requested word you could open and read the contents of the file. Replace any occurrences of the word with blank text. Then write back to the file.

file=open('test_words.txt','r')         # Open the file in read mode
fileText = file.read()                  # Read in the contents to a string variable
file.close()                            # Close the file as you cant write to it in read mode
fileText = fileText.replace(remove, '') # Replace any occurances of the word the user wants to remove with a blank string
file=open('test_words.txt', 'w')        # Open the file again, but this time in write mode
file.write(fileText)                    # Write the modified text back to the file
file.close()                            # Close the file

Searching on stack overflow there seems to be answers to this question already: How to search and replace text in a file?

newToCoding
  • 174
  • 1
  • 1
  • 8
  • Sorry that didn't work, Getting this error: Traceback (most recent call last): File "my file", line 39, in changewords() File "my file", line 22, in changewords file.open('test_words.txt','w') AttributeError: '_io.TextIOWrapper' object has no attribute 'open' – Qu1ppy Jun 02 '21 at 00:15
  • @Qu1ppy, my bad I missed typed. replace `file.open('test_words.txt,'w')` with `file=open('test_words.txt,'w')`. I'll update answer as well. – newToCoding Jun 02 '21 at 08:13