1

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"))
1
  • So your script truncates the file: "program.py" to zero size, then queries the file size (its 0) and returns that. Did you mean to write the comments to the file at all? Commented Jun 17, 2020 at 17:03

3 Answers 3

3
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"))
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.