python - 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 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/

相关文章:

Python 多重处理

python - Plist一直加载不结束,满足条件也不退出

python - 在两个 Arduino Mega 上用 pyfirmata 读取模拟值的问题

python pandas-将带有两个参数的函数应用于列

python - 提取MSER检测到的区域(Python,OpenCV)

python - xml.etree.ElementTree iterparse() 仍在使用大量内存?

python - 迭代列并在达到特定数字时返回列名称

python - pandas 中的频率表(如 R 中的 plyr)

python - 如何在 PyPI 项目中存储 API key ?

javascript - 通过 HTMLParser 验证 Google 优化器 javascript 代码