Skip to content

[Python] Use built-in "os" module to traversal every file and count the file size

Last Updated on 2021-06-02 by Clay

Introduction

"os" is a Python package and it can help us to implement many infrastructure operators.

Today I want to traversal all file in my computer and count their size. So I use "os" package to do it. And I recorded it.

Ok, it's go!


some functions of os

First, we have to know what are the functions they called listdir(), isdir(), getsize().

Suppose I had a folder named "test", and there are three document in it.

We can use "os.listdir()" to show all file in the folder.

# -*- coding: utf-8 -*-
import os

print(os.listdir('test'))



Output:

['1.txt', '2.txt', '3.txt']

Yes, we saw them!

And then, we can determine if these files are folders by "os.path.isdir()".

# -*- coding: utf-8 -*-
import os

path = 'test'
print('Is "{}" a dictionary?'.format(path), os.path.isdir(path))

for fileName in os.listdir(path):
    print('Is "{}" a dictionary?'.format(fileName), os.path.isdir(path+'/'+fileName))



Output:

Is "test" a dictionary? True
Is "1.txt" a dictionary? False
Is "2.txt" a dictionary? False
Is "3.txt" a dictionary? False

Finally, we can use "getsize()" to return the size of file (bytes).

(I wrote some sentence in the file.)

Not so elegant, sorry.

And we fix some code:

# -*- coding: utf-8 -*-
import os

path = 'test'
print('"{}"'.format(path), os.path.getsize(path))

for fileName in os.listdir(path):
    print('"{}"'.format(fileName), os.path.getsize(path+'/'+fileName))



Output:

"test" 0
"1.txt" 14
"2.txt" 0
"3.txt" 0

Traversal all files

My code:

# -*- coding: utf-8 -*-
import os


def check(path):
    folders = []
    path = path

    try:
        for file in os.listdir(path):
            filePath = path+'/'+file

            if os.path.isdir(filePath):
                print(file, os.path.getsize('{}'.format(filePath)))
                folders.append(filePath)
            else:
                print(file, os.path.getsize('{}'.format(filePath)))
    except:
        print('PermissionError')

    for folder in folders:
        check(folder)


if __name__ == '__main__':
    check('C:/')



We done!

Tags:

Leave a Reply