sandu r
sandu r

Reputation: 17

Incorrect size of file in Python

Consider:

import os

def create_python_script(filename):
    comments = "# Start of a new Python Program"
    #filesize = 0
    with open(filename, 'w') as new_file:
        new_file.write(comments)
        cwd = os.getcwd()
        fpath = os.path.abspath(filename)
        filesize = os.path.getsize(fpath)
    return(filesize)

print(create_python_script('newprogram.py'))

I am getting the result as zero, but it should get "31".

Upvotes: 2

Views: 2698

Answers (4)

SSV 1
SSV 1

Reputation: 33

This one is working perfectly too!

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

Upvotes: -1

Aarju Raj Arya
Aarju Raj Arya

Reputation: 1

import os

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

print(create_python_script("program.py"))

#this will give you correct result

Upvotes: -1

aro01
aro01

Reputation: 11

First opening the file with write permissions to add the text in the file. Then opening the file with read permissions to get the size of the file.

import os

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

    with  open(filename, "r"):
        filesize = os.path.getsize(filename)
        print(filesize)
    return filesize

print(create_python_script("program.py"))

Upvotes: 0

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

You didn't close your file before trying to get its size, as you do it inside the with block. Take it outside:

import os

def create_python_script(filename):
    comments = "# Start of a new Python Program"
    #filesize = 0
    with open(filename, 'w') as new_file:
        new_file.write(comments)
        cwd=os.getcwd()
        fpath = os.path.abspath(filename)
        print(fpath)

    filesize=os.path.getsize(fpath)
    return(filesize)

print(create_python_script('newprogram.py'))
# 31

Upvotes: 3

Related Questions