Search code examples
pythonpython-3.7

How to get individual File Size from cwd in Python


still very new to programming and learning the basics, any help is greatly appreciated.

import os

path = os.getcwd()
print(os.listdir(path))
os.path.getsize(path)
print(os.path.getsize(path))

When I run the above program I get this output:

['Lab3_Exercise1.py', 'Lab3_Exercise2.py', 'Lab3_Exercise4.py', 'Lab3_Exercose3.py']
4096

How would I go about separating out each file individually in the output rather than just getting a total file size? Code should include only the import os module if possible and be universal where it could tell any user each individual file size of their current working directory. Thank you for the help.

Output should be similar to:

file: Lab3_Exercise1.py size:
file: Lab3_Exercise2.py size:
file: Lab3_Exercise3.py size:
file: Lab3_Exercise4.py size:

Solution

  • While the other answers work, they also include directories in the list of "files". If you want to exclude them you can use os.path.isfile(f) like this:

    import os
    
    path = os.getcwd()
    files = [f for f in os.listdir(path) if os.path.isfile(f)]
    for f in  files:
        print(f, "-", os.path.getsize(f))
    

    which outputs:

    comb.py - 228
    list_ex.py - 348
    so_cwd_size.py - 145
    matrix_test.py - 173
    thread_test.py - 847