为了账号安全,请及时绑定邮箱和手机立即绑定

蟒蛇中的文件大小不正确

蟒蛇中的文件大小不正确

炎炎设计 2022-10-05 09:36:36
import osdef 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”
查看完整描述

4 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

在尝试获取文件大小之前,您没有关闭文件,就像在块内所做的那样。把它带到外面: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


查看完整回答
反对 回复 2022-10-05
?
慕容森

TA贡献1853条经验 获得超18个赞

import os


def create_python_script(filename):

  comments = "# Start of a new Python program"

  with open(filename, 'w') as file:

    file.write(comments)

    file.close()

    filepath = os.path.abspath(filename)

    filesize = os.path.getsize(filepath)

  return(filesize)


print(create_python_script("program.py"))


#this will give you correct result


查看完整回答
反对 回复 2022-10-05
?
12345678_0001

TA贡献1802条经验 获得超5个赞

这个也工作得很好!


    def create_python_script(filename):

      import os

      comments = "# Start of a new Python program"

      with open(filename,'w')as file:

         file.write(comments)

      filesize = os.path.getsize(filename)

      return(filesize)

    print(create_python_script("program.py"))


查看完整回答
反对 回复 2022-10-05
?
慕少森

TA贡献2019条经验 获得超9个赞

首先打开具有写入权限的文件,以在文件中添加文本。然后以读取权限打开文件以获取文件的大小。


import os


def create_python_script(filename):

    comments = "# Start of a new Python program"

    with open(filename, 'w') as pd:

        pd.write(comments)


    with  open(filename, "r"):

        filesize = os.path.getsize(filename)

        print(filesize)

    return filesize


print(create_python_script("program.py"))


查看完整回答
反对 回复 2022-10-05
  • 4 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信