创建一个 python 脚本 returns 新文件的大小

Creating a python script that returns the size of a new file

我正在尝试 create_python_script 函数在当前工作目录中创建一个新的 python 脚本,向其添加由 'comments' 变量声明的注释行,并且returns 新文件的大小。我得到的输出是 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"))

您忘记实际写入文件,因此它不会包含任何内容。要记住的另一件重要事情是,文件在 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"))

请注意,输入参数以前未使用过,现在已更改。

def create_python_script(filename):
  comments = "# Start of a new Python program"
  with open(filename, 'w') as file:
    filesize = file.write(comments)
  return(filesize)

print(create_python_script("program.py"))

练习中有一个流氓缩进:

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

print(create_python_script("program.py"))

应该是:

import os
def create_python_script(filename):
  comments = "# Start of a new Python program"
  with open(filename, "a") as newprogram:
    newprogram.write(comments)
  filesize = os.path.getsize(filename) #Error over here
  return(filesize)

print(create_python_script("program.py"))

我刚完成。