返回的文件大小始终为0

2024-05-03 18:58:38 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我有一段代码,在python脚本中添加一行代码,然后计算它的大小,结果很好

import os
def create_python_script(filename):
  comments = " Start of a new Python program"
  with open(filename,'w') as f :
    f.write(comments)
    f.close
    filesize = os.path.getsize(filename)
  return(os.path.getsize(filename))

print(create_python_script("program.py"))

它输出30,这是文件的实际大小,因为它是空的,并且只有那一行

现在,如果我将return(os.path.getsize(filename))更改为return(filesize),这是合乎逻辑的,因为filesize = os.path.getsize(filename)我实际上得到了输出0

下面是进行更改的第二个代码

import os
def create_python_script(filename):
  comments = " Start of a new Python program"
  with open(filename,'w') as f :
    f.write(comments)
    f.close
    filesize = os.path.getsize(filename)
  return(filesize)

print(create_python_script("program.py"))

有人能解释一下为什么输出为0吗

多谢各位


Tags: ofpath代码importreturnosdefcreate
3条回答

更正

  • 我已经删除了f.close,当您使用with open()时,它不是必需的
  • 注意,filesize = os.path.getsize(filename)的缩进

工作代码

import os
def create_python_script(filename):
    comments = " Start of a new Python program"
    with open(filename,'w') as f :
        f.write(comments)

    filesize = os.path.getsize(filename)
    return filesize

print(create_python_script("program.py"))

我可能错了,但是当“with”函数打开时,它不会“更新文件”,所以请尝试从“with”函数中删除getsize

filesize返回0的原因非常简单。正如评论所说,这与范围和/或文件关闭无关。再看看你的代码-

(删除f.close首先:它什么也不做,第二:当使用with open打开文件时,不需要手动关闭文件)

with open(filename,'w') as f :
    f.write(comments)
    filesize = os.path.getsize(filename)
  return os.path.getsize(filename)

请注意返回值,getsize是在文件写入并关闭后计算的,即with之外。在with之后,文件已完成写入,并且其实际大小已更新-因此,这是您应该计算大小的时间

现在看一看替代方案-

with open(filename,'w') as f :
    f.write(comments)
    filesize = os.path.getsize(filename)
  return filesize

在哪里计算.getsize之前文件已关闭-因此文件尚未写入,当前大小为0,因为文件在写入之前为空

事实上,试试这个-

with open(filename,'w') as f :
    f.write(comments)
    print(os.path.getsize(filename))
  return os.path.getsize(filename)

输出-

0
30

看到了吗.getsizewith内返回0,因为它应该返回0

这才是真正的原因。希望这能澄清你的问题。这绝对与“范围”无关

相关问题 更多 >