作者:
uranusjr (â†é€™äººæ˜¯è¶…級笨蛋)
2016-05-02 17:05:04※ 引述《doomleika (iSuck)》之銘言:
: import os
: from os.path import join, abspath
:
: def get_path(directory, file):
: return abspath(join(directory, file))
:
: # Put your directory here
: directory = "C:/path/to/your/directory"
:
: directories = os.walk(directory)
: text_list = []
:
: for directory, _, files in directories:
: for a_file in files:
: file_path = get_path(directory, a_file)
: with open(file_path, 'r') as f:
: text_list.append(f.read())
→ doomleika: 請問Python 3要怎麼寫 ._.? 05/02 10:34
大概像這樣
import pathlib
dirpath = pathlib.Path('C:/path/to/your/directory')
text_list = [p.read_text() for p in dirpath.rglob('*') if p.is_file()]
其實 glob 在 Python 2 也有(glob module), 不過 pathlib 在讀檔上方便很多