【发布时间】:2020-07-25 17:30:12
【问题描述】:
当我尝试使用 os.path.getsize() 时得到“0”输出
不确定出了什么问题,使用 PyCharm,我看到文件已创建并且“cmets”已添加到文件中。但是 PyCharm 显示输出“0”:(
代码如下:
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, "w") as file:
file.write(comments)
filesize = os.path.getsize(filename)
return(filesize)
print(create_python_script("program.py"))
请指出我没有看到的错误。
【问题讨论】:
-
尝试在文件关闭后获取文件大小,即在
with open(...)之外 -
是的,这是工作。谢谢!
-
在上下文管理器之外使用 filesize = os.path.getsize(filename)
-
由于这是通过取消缩进
filesize来解决的,因此我投票结束由于错字/不可重现的问题。
标签: python python-3.x os.path