lundi 23 septembre 2019

Save string from variable to .txt and check if variable matches already used string on next loop

I hope someone can help me here.

I have a Python 3 program to pick a random word from words.txt and then work with it after that. That bit works.

Then I need to filter the words - to make sure it doesn't use the same word twice and to make sure explicit words aren't used.

Words that have already been used are stored in UsedWords.txt when they are used for the first time. Then read the next time the program is run to check that the same word isn't used again.

Words that cannot be used at all are stored in BlockedWords.txt. This is a static file and does not need to be edited.

When running my code, I get this error:

Traceback (most recent call last): File "program.py", line 43, in used.write(randomStr + '\n') io.UnsupportedOperation: not writable

The part of my code responsible for the actions above currently looks like this:

#Picks Random Word
        with open('words.txt') as list:
                #Scan The File
                lines = list.readlines()
                #Set randomStr As The Generated String
                randomStr = random.choice(lines)
                #Set randomStr As A String And Keeps The Original Value
                randomStr = str(randomStr)
                #Remove Blank Line After The Word
                randomStr = randomStr.replace("\n", "")
                #Save Word To Text File Of Used Words
                used = open('UsedWords.txt')
                used.write(randomStr + '\n')
                print(colour.BOLD, colour.RED, 'Added Used Word To Used List')

        #Checks For Already Used Word
        if randomStr in used:
                print(colour.BOLD, colour.BLUE, 'Word already used, restarting...')
                print(randomStr)
                continue

        #Checks For Blocked Word
        with open('BlockedWords.txt') as blocked:
                if randomStr in blocked:
                        print(colour.BOLD, colour.BLUE, 'Blocked word, restarting...', colour.END)
                        print(tweet)
                        continue




Aucun commentaire:

Enregistrer un commentaire