inkblot
inkblot

Reputation: 113

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

Upvotes: 1

Views: 9965

Answers (3)

user18626315
user18626315

Reputation: 11

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.

Upvotes: 1

vasu
vasu

Reputation: 39

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

Upvotes: 3

Johan
Johan

Reputation: 80

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.

Upvotes: 2

Related Questions