1. 程式人生 > 其它 >Python使用遞迴+遍歷讀取資料夾下所有docx檔案

Python使用遞迴+遍歷讀取資料夾下所有docx檔案

技術標籤:Python基礎知識python

文章目錄

思路

首先遍歷父資料夾下所有內容,如果內容是檔案+【其他條件,如讀取PDF,Excel】則直接讀取,不是檔案則遞迴重複上一步操作。

資料夾結構

話不多說,上菜!先給大家展示一下檔案結構如下:

檔案結構
實現程式碼如下:

print(os.getcwd().rsplit('\\')[-1])
for i in os.listdir(os.getcwd()):
    if os.path.isdir(i):
        print('\t{}'.format(i))
        for
file in os.listdir(i): print('\t\t',file) else: print(i)

遞迴+遍歷讀取想要的檔案

用一個dataframe記錄,檔名和對應內容,最終結果如下:
具體內容
對應程式碼如下:

def read_word(cur_dir):
    for sub_file in os.listdir(cur_dir):
    	# 遍歷該資料夾下所有內容,可能有各自檔案或者資料夾
        sub_file_abs_path = os.path.join(cur_dir, sub_file)  # 拼為完整路徑,方便後面使用
        if
os.path.isfile(sub_file_abs_path): # 判斷是否為檔案, 如果是檔案,拼接完整path file_path = os.path.join(cur_dir, sub_file) if file_path.rsplit('.')[-1] == 'docx': # 判斷是否是docx檔案 fp = docx.Document(file_path) content = "" for
p in fp.paragraphs: content += p.text data.loc[len(data)] = [file_path.rsplit('\\')[-1], content] else: sub_folder_path = os.path.join(cur_dir, sub_file) read_word(sub_folder_path)

友情提示:博主也是學習路上的一員,程式碼可能不是最優最簡潔,但親測有效。如果讀者覺得有幫助則借鑑,可以完善的地方希望能多多指教一起學習。思路來源感謝Allan。