簡體   English   中英

Python:如何讀取目錄中的所有文件

[英]Python: How to read all files in a directory

我發現這段代碼可以讀取特定文件的所有行。

如何編輯它以使其一一讀取目錄“文件夾”中的所有文件(html、文本、php .etc),而不必指定每個文件的路徑? 我想在目錄中的每個文件中搜索關鍵字。

 path = '/Users/folder/index.html'
    files = glob.glob(path)
    for name in files:  
        try:
            with open(name) as f:  
                sys.stdout.write(f.read())
        except IOError as exc:
            if exc.errno != errno.EISDIR:  
                raise 
import os
your_path = 'some_path'
files = os.listdir(your_path)
keyword = 'your_keyword'
for file in files:
    if os.path.isfile(os.path.join(your_path, file)):
        f = open(os.path.join(your_path, file),'r')
        for x in f:
            if keyword in x:
                #do what you want
        f.close()

os.listdir('your_path')將列出目錄的所有內容
os.path.isfile將檢查其文件與否

更新 Python 3.4+

讀取所有文件

from pathlib import Path

for child in Path('.').iterdir():
    if child.is_file():
        print(f"{child.name}:\n{child.read_text()}\n")

讀取按擴展名過濾的所有文件

from pathlib import Path

for p in Path('.').glob('*.txt'):
    print(f"{p.name}:\n{p.read_text()}\n")

讀取按擴展名過濾的目錄樹中的所有文件

from pathlib import Path

for p in Path('.').glob('**/*.txt'):
    print(f"{p.name}:\n{p.read_text()}\n")

或者等效地,使用Path.rglob(pattern)

from pathlib import Path

for p in Path('.').rglob('*.txt'):
    print(f"{p.name}:\n{p.read_text()}\n")

路徑.open()

作為Path.read_text() [或二進制文件的Path.read_bytes() ] 的替代方法,還有Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None) ,這就像 Python 的內置函數open()

from pathlib import Path

for p in Path('.').glob('*.txt'):
    with p.open() as f:
        print(f"{p.name}:\n{f.read()}\n")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM