[英]Python: How to read all files in a directory
I found this piece of code that reads all the lines of a specific file.我发现这段代码可以读取特定文件的所有行。
How can I edit it to make it read all the files (html, text, php .etc) in the directory "folder" one by one without me having to specify the path to each file?如何编辑它以使其一一读取目录“文件夹”中的所有文件(html、文本、php .etc),而不必指定每个文件的路径? I want to search each file in the directory for a keyword.
我想在目录中的每个文件中搜索关键字。
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')
will list all content of a directory os.listdir('your_path')
将列出目录的所有内容os.path.isfile
will check its file or not os.path.isfile
将检查其文件与否
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")
Or equivalently, use Path.rglob(pattern)
:或者等效地,使用
Path.rglob(pattern)
:
from pathlib import Path
for p in Path('.').rglob('*.txt'):
print(f"{p.name}:\n{p.read_text()}\n")
As an alternative to Path.read_text()
[or Path.read_bytes()
for binary files], there is also Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)
, which is like the built-in Python function 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.