python Method for Viewing File Size and Folder Contents

  • 2021-07-10 20:23:20
  • OfStack

1 Once you have a way to process file paths, you can start collecting information about specific files and folders. The os. path module provides functions to view the number of bytes of a file and the files and subfolders in a given folder.

Calling os. path. getsize (path) returns the number of bytes of the file in the path parameter.

Calling os. listdir (path) returns a list of file name strings containing each file in the path parameter (note that this function is in the os module, not os. path).

Here are the results of my attempts at these functions in an interactive environment:


>>> os.path.getsize('C:\\Windows\\System32\\calc.exe')
776192
>>> os.listdir('C:\\Windows\\System32')
['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',
--snip--
'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']

As you can see, the calc. exe program on my computer is 776192 bytes. There are many files under my C:\ Windows\ system32. If you want to know the total number of bytes for all files in this directory, you can use both os. path. getsize () and os. listdir ().


>>> totalSize = 0
>>> for filename in os.listdir('C:\\Windows\\System32'):
totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32', filename))
>>> print(totalSize)
1117846456

As you loop through each file in the C:\ Windows\ System32 folder, the totalSize variable increases the number of bytes per file in turn. Note that when I called os. path. getsize (), I used os. path. join () to connect the folder name to the current file name. The integer returned by os. path. getsize () is added to totalSize. After iterating through all the files, I print out totalSize to see the total number of bytes in the C:\ Windows\ System32 folder.


Related articles: