一、os.walk()
Python提供了os.walk()方法可以方便地遍歷文件夾中的所有文件。os.walk()方法需要傳入一個參數rootdir,即需要遍歷的文件夾的路徑。它會返回一個三元的元組,其中第一個元素是當前文件夾的路徑,第二個元素是當前文件夾中所有子文件夾的名稱,第三個元素是當前文件夾中所有文件的名稱。我們可以利用這個三元元組遞歸遍歷整個文件夾中的所有文件和文件夾。
import os def list_files(startpath): for root, dirs, files in os.walk(startpath): level = root.replace(startpath, '').count(os.sep) indent = ' ' * 4 * level print('{}{}/'.format(indent, os.path.basename(root))) subindent = ' ' * 4 * (level + 1) for file in files: print('{}{}'.format(subindent, file)) list_files('path/to/folder')
上面的代碼會從指定的文件夾中遞歸遍歷文件夾中的所有文件和文件夾,並打印它們的相對路徑。它使用了字符串的乘法運算符 * 來生成空格,從而實現縮進的效果。
二、glob.glob()
除了os.walk()方法外,Python還提供了glob.glob()方法,可以用來匹配特定模式的文件名。它需要傳入一個包含通配符的字符串,然後返回匹配該模式的所有文件名。
import glob for file in glob.glob('path/to/folder/*'): print(file)
上面代碼中,我們使用通配符 * 匹配了path/to/folder/文件夾中的所有文件名,並打印它們。
三、遞歸遍歷文件夾的擴展應用
在遞歸遍歷文件夾的基礎上,我們還可以實現一些更加複雜的功能。比如,統計指定文件夾中所有文件的大小,並按照文件類型進行分類。
import os def get_size(startpath): total_size = 0 file_dict = {} for root, dirs, files in os.walk(startpath): for file in files: path = os.path.join(root, file) size = os.path.getsize(path) total_size += size ext = os.path.splitext(file)[1] if ext not in file_dict: file_dict[ext] = 0 file_dict[ext] += size for ext, size in file_dict.items(): print(f"{ext}: {size/1024/1024:.2f} MB") print(f"Total size: {total_size/1024/1024:.2f} MB") get_size('path/to/folder')
上面的代碼會遞歸遍歷文件夾並統計其中所有文件的大小,並按照文件類型進行分類和匯總。我們使用了os.path.splitext()方法來獲取文件的擴展名,並使用了字典來進行文件類型和文件大小的統計。
四、完整代碼示例
下面是一個完整的例子,演示了如何遞歸遍歷文件夾並打印所有文件的相對路徑:
import os def list_files(startpath): for root, dirs, files in os.walk(startpath): level = root.replace(startpath, '').count(os.sep) indent = ' ' * 4 * level print('{}{}/'.format(indent, os.path.basename(root))) subindent = ' ' * 4 * (level + 1) for file in files: print('{}{}'.format(subindent, file)) list_files('path/to/folder')
如果我們想要按文件類型分類並統計文件大小的話,可以使用如下代碼:
import os def get_size(startpath): total_size = 0 file_dict = {} for root, dirs, files in os.walk(startpath): for file in files: path = os.path.join(root, file) size = os.path.getsize(path) total_size += size ext = os.path.splitext(file)[1] if ext not in file_dict: file_dict[ext] = 0 file_dict[ext] += size for ext, size in file_dict.items(): print(f"{ext}: {size/1024/1024:.2f} MB") print(f"Total size: {total_size/1024/1024:.2f} MB") get_size('path/to/folder')
這個代碼會遍歷指定的文件夾,並打印出其中所有文件按照後綴名分別的大小和總大小。
總結
通過本文的介紹,我們學習了Python中的兩種遍歷文件夾的方法,分別是os.walk()和glob.glob()方法。此外,我們還演示了遞歸遍歷文件夾的擴展應用,並通過完整的代碼示例對這些內容進行了說明。通過本文的學習,相信你已經掌握了在Python中遍歷文件夾的基本方法和一些應用技巧。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/300414.html