Python认为我的文件是空的,即使它是';不是
因此,我使用以下代码检查我的文件是否为空:Python认为我的文件是空的,即使它是';不是,python,file,Python,File,因此,我使用以下代码检查我的文件是否为空: 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: newPrizeP
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()
如果文件为空,则创建一个新文件,并输入变量prizePool和Win。如果不是空的,我尝试从文件中提取不同行上的值,并将它们分配给变量。然而,即使我的文件显然不是空的,我的代码也总是在“else”通道上运行。
我做错了什么?使用
PrizePool.txt
的完整路径-例如“C:\\Users\\ThisUser\\PrizePool.txt”
根据,
os.stat()
接受完整路径,而不是文件名。您能指出fileEmpty
的分配位置吗?您的缩进也不正确。fileEmpty是函数吗?如果是这样的话,你应该通过添加paren来调用它。i、 e.fileEmpty()或可能的fileEmpty(f)打开文件进行追加。您应该通过类似于os.path.getsize(“/foo/bar/file”)
的方式检查文件sys。对不起,伙计们。FileEmpty作为一个函数只是一个测试,我现在把它改回来了。为什么我的缩进不正确(如果是,那么这与复制+粘贴到stackoverflow中有关)?为什么要先读取文件,然后检查它是否为空?这很奇怪,因为在我删除data=f.read()后,它现在可以工作(至少检查空性)。这是一个较旧的版本,它遍历了整个文件,留下文件的其余部分(空)供检查。