Python: 如何读取目录中的所有文件?
我找到了一段代码,它可以读取一个特定文件的所有行。
我该怎么修改这段代码,让它能一个一个地读取“folder”文件夹里的所有文件(比如html、文本、php等),而不需要我一个个指定每个文件的路径呢?我想在每个文件里搜索一个关键词。
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
2 个回答
23
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
这个命令会检查你给定的路径是不是一个文件。
27
更新 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")
Path.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")