蟒蛇中的文件大小不正确

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”


炎炎设计
浏览 129回答 4
4回答

BIG阳

在尝试获取文件大小之前,您没有关闭文件,就像在块内所做的那样。把它带到外面:withimport 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)        print(fpath)    filesize=os.path.getsize(fpath)    return(filesize)print(create_python_script('newprogram.py'))# 31

慕容森

import osdef 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

12345678_0001

这个也工作得很好!    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"))

慕少森

首先打开具有写入权限的文件,以在文件中添加文本。然后以读取权限打开文件以获取文件的大小。import osdef 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 filesizeprint(create_python_script("program.py"))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python