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
block 中执行的那样。把它带到外面:
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
关于python - python中文件大小不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61154609/