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

I'm trying to create_python_script function that creates a new python script in the current working directory, adds the line of comments to it declared by the 'comments' variable, and returns the size of the new file. The output I get is 0 but should be 31. Not sure what I'm doing wrong.

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


Solution 1:[1]

You forgot to actually write to the file, so it won't contain anything. Another important thing to keep in mind, is that the file is closed automatically after the with statement. In other words: nothing is written to the file until the with statement ends, so the file size is still zero in your program. This should work:

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

Note that the input argument was unused previously and has now been changed.

Solution 2:[2]

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

Solution 3:[3]

There is a rogue indent in the exercise:

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

It should be:

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

I just finished myself.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Johan
Solution 2 quamrana
Solution 3 user18626315