Carniv0re YT
Carniv0re YT

Reputation: 43

Python thinks my file is empty even though it's not

so I'm using this code to check whether my file is empty:

def getPrizePool():
    global prizePool
    global win
    f = open("PrizePool.txt", "a+")
    data = f.read()
    if os.stat("PrizePool.txt").st_size==0:
        prizePool = 0
        setPrizePool()
    else:
        newPrizePool = int(f.readline(1))
        prizePool = newPrizePool

        newWin = int(f.readline(2))
        win = newWin
    f.close()

If the file is empty, create a new file and enter the variables prizePool and Win into it. if it's not empty, I try to extract the values, which are on different lines, from the file and assign them to the variables. However, my code always goes down the "else" lane, even thouth my file clearly is not empty. What am I doing wrong?

Upvotes: 1

Views: 530

Answers (2)

conchita
conchita

Reputation: 11

You have the same exact problem like I had. Still don't know why filename.read() make Python consider my file empty.

My solution is to close and open the file again

Upvotes: 0

alex
alex

Reputation: 7453

Use the full path to PrizePool.txt - e.g. "C:\\Users\\ThisUser\\PrizePool.txt".

Per the Python documentation on os.stat, os.stat() accepts a full path, not a file name.

Upvotes: 1

Related Questions