首页 > 解决方案 > 返回文件大小总是得到 0

问题描述

所以基本上我有这段代码在python脚本中添加一行,然后计算它的大小,它工作正常

import os
def create_python_script(filename):
  comments = " Start of a new Python program"
  with open(filename,'w') as f :
    f.write(comments)
    f.close
    filesize = os.path.getsize(filename)
  return(os.path.getsize(filename))

print(create_python_script("program.py"))

它输出 30 这是文件的实际大小,因为它是空的并且只有那一行

现在如果我改变 return(os.path.getsize(filename))with return(filesize)which 是合乎逻辑的,因为filesize = os.path.getsize(filename)我实际上得到了输出 0

这是进行更改的第二个代码

import os
def create_python_script(filename):
  comments = " Start of a new Python program"
  with open(filename,'w') as f :
    f.write(comments)
    f.close
    filesize = os.path.getsize(filename)
  return(filesize)

print(create_python_script("program.py"))

有人可以向我解释为什么输出为 0 吗?

谢谢你

标签: pythonfilesizeos.path

解决方案


我可能错了,但是当“with”功能打开时,它不会“更新文件”,所以尝试从“with”功能中删除getsize


推荐阅读