Python thinks my file is empty even though it's not
Question:
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?
Answers:
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.
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
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?
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.
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