Skip to content

[Python] 使用 os 模組遍歷所有檔案,並計算檔案大小

os 模組可以視為一個 Python 自帶的函式庫,可以幫助我們使用 Python 實現許多系統層級的操作。

今天因為自己的需求,希望能夠遍歷自己磁碟區底下所有的檔案,故找了一些教學,並自己實現了個遍歷所有檔案並計算大小的程式。

以下,便開始紀錄該如何使用 Python 中的 os 來遍歷檔案吧!


os 的各種功能

首先,我們要知道 listdir()isdir() 以及 getsize() 這三個函式的功能。

假設我有個名叫 test 的資料夾,底下有三份檔案。

然後我們使用 os.listdir() 來指定我們要查看的資料夾。

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

print(os.listdir('test'))


Output:

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

如何?我們似乎可以使用 listdir() 這個指令找到資料夾底下的所有資料。

緊接著,我們判斷一下這些檔案是不是一個『資料夾』。

這次,我們使用 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

首先,我們判斷 path 這個變數 —— 也就是 test 資料夾是不是個資料夾?答案是 True。

然後,我們用剛剛學會的 listdir 來找出這個資料夾底下的所有檔案,並判斷是不是『資料夾』。

當然,答案是否定的。

最後便是 getsize(),這個 function 可以返回檔案的大小(位元組)。

為了讓每個檔案有著不一樣的大小,我們在 1.txt 進行了些微的修改。

不太文雅,抱歉。

然後我們稍微修改一下剛才的程式碼:

# -*- 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

這次,我們同樣計算 test 資料夾、以及底下三個檔案的大小。這次我們可以看到,1.txt 是唯一擁有大小的檔案。


遍歷檔案

直接附上程式碼。因為 Output 太長,這次我就不貼啦。

# -*- 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:/')
Tags:

Leave a Reply