首页 > 解决方案 > 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”

标签: python

解决方案


在尝试获取文件大小之前,您没有关闭文件,就像在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

推荐阅读