python - 返回文件大小总是得到 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 吗?
谢谢你
解决方案
我可能错了,但是当“with”功能打开时,它不会“更新文件”,所以尝试从“with”功能中删除getsize
推荐阅读
- perl - 使用 Date::Calc 的年份和日期
- javascript - 我怎样才能让统计框显示在我的threejs画布上?
- swift - 将 viewDidLoad() 或 ViewDidAppear() 中的变量传递给按钮操作
- php - 谷歌地图 api 标记、sql 和 xml
- rest - Servicenow 与 SAP 的集成
- c - 为什么我在 C 中遇到分段错误?
- excel - Excel VBA宏读取具有不同文本的一列
- odata - sap.m.table 未更新
- google-bigquery - BigQuery 是否可以使用 aes_decrypt 函数?
- botframework - 部署自定义网络聊天机器人框架