创建返回新文件大小的python脚本

问题描述 投票:1回答:1

我正在尝试create_python_script函数,该函数在当前工作目录中创建一个新的python脚本,向其中添加由'comments'变量声明的注释行,并返回新文件的大小。我得到的输出是0,但应该是31。不确定我在做什么错。

    import os

def create_python_script(filename):
  comments = "# Start of a new Python program"
  with open("program.py", "w") as file:
    filesize = os.path.getsize("/home/program.py")
  return(filesize)

print(create_python_script("program.py"))
python operating-system filesize
1个回答
0
投票
您忘了实际写入文件,因此它不包含任何内容。要记住的另一件事是,在with语句之后文件自动关闭。换句话说:在with语句结束之前,不会将任何文件写入文件,因此程序中的文件大小仍为零。这应该工作:

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"))

请注意,输入参数以前未使用,现在已更改。    
© www.soinside.com 2019 - 2024. All rights reserved.