python - python中文件的大小不正确
问题描述
import os
def create_python_script(filename):
comments = "# Start of a new Python Program"
#filesize = 0
with open(filename, 'w') as new_file:
new_file.write(comments)
cwd=os.getcwd()
fpath = os.path.abspath(filename)
filesize=os.path.getsize(fpath)
return(filesize)
print(create_python_script('newprogram.py'))
我得到的结果为零,但它应该得到“31”
解决方案
在尝试获取文件大小之前,您没有关闭文件,就像在with
块内执行此操作一样。把它带到外面:
import os
def create_python_script(filename):
comments = "# Start of a new Python Program"
#filesize = 0
with open(filename, 'w') as new_file:
new_file.write(comments)
cwd=os.getcwd()
fpath = os.path.abspath(filename)
print(fpath)
filesize=os.path.getsize(fpath)
return(filesize)
print(create_python_script('newprogram.py'))
# 31
推荐阅读
- angular - Angular 6 使用新的 RxJS 处理 403 响应
- php - laravel 中是否有用于身份验证登录的默认 URL?
- vue.js - 切换语言 VueI18n
- angular - 具有包含“:”的属性的 Json 响应
- spring-boot - 如何在 WildFly 10 中将爆炸战争部署为文件夹
- google-cloud-dataflow - PubSub 水印不前进
- git - 如何通过 azure cli 执行我的 git 存储库中的 shell 脚本
- php - php 7.0 不上传文件
- c# - 如何在针对 SQL Server 执行之前使用 AutoMapper 过滤列
- php - 如何在 laravel 5.3 中使用插入存储过程获取插入的 ID?