.txt file opened in python won't itterate properly

Advertisements

The following contains abridged version of the code for a text card game I am trying to run. It should get a random string for a card from a random line in "cards.txt", and add it to a user’s collection at "user.txt" (user would be the name of the user). A sample line from "users.txt" should look like:
X* NameOfCard
If "user.txt" alreasy contains an entry for a card, it changes the number before the name by 1. If "user.txt" had:
1* Hyper Dragon
then got another Hyper Dragon, the line would look like:
2* Hyper Dragon
If there is no version already in there, it should append a newline that says:
1* NameOfCard

The code however, is flawed. No matter what, it will always change the contents of "users.txt" to:
1* NameOfCard(followed by 3 blank lines). I belive the issue to lie in the marked for loop in the following code:

from random import choice
def check(e, c):
    if (c in e):
        return True
    else:
        return False
username = input("What is the username?: ")
collectionPath = f"collections\\{username}.txt"

while True:
    with open("cards.txt", "r") as cards:
        card_drew = f"{choice(cards.readlines())}\n"
        print("Card drawn: "+card_drew)

    with open(collectionPath, "w+") as file:
        copyowned = False
        print("Looking for card")
        currentline = 0
        for line in file:
            # this is the marked for loop.
            print("test")
            print("checking "+line)
            currentline += 1
            if (check(card_drew, line)):
                print("Found card!")
                copyowned = True
                strnumof = ""
                for i in line:
                    if (i.isdigit()):
                        strnumof = strnumof+i
                numof = int(strnumof)+1
                line = (f"{numof}* {card_drew}")
                print("Card added, 2nd+ copy")

    if (not copyowned):
        with open(collectionPath, "a") as file:
            file.write(f"1* {card_drew}\n")
            print("Card Added, 1st copy")
    input(f"{username} drew a(n) {card_drew}")

When I run it, the for loop act as if it’s not there. It wont even run a print function, though an error message never appears. After using try and except statements, the loop still doesn’t porvide an error. I have no clue why it’s doing this.

Some help would be greatly appreciated.

>Solution :

open(collectionPath, "w+") Opens a file in read and write mode. It creates a new file if it does not exist, if it exists, it erases the contents of the file and the file pointer starts from the beginning.

So essentially you are erasing the contents of your file, and thus cannot read anything from it. You probably wish to open it in read mode instead: open(collectionPath, "r")

Maybe this diagram can be useful for you: Difference between modes a, a+, w, w+, and r+ in built-in open function?

Leave a ReplyCancel reply