gpt4 book ai didi

python - python中文件大小不正确

转载 作者:行者123 更新时间:2023-12-04 10:14:15 26 4
gpt4 key购买 nike

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

关于python - python中文件大小不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61154609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com