简体   繁体   English

Python:如何读取目录中的所有文件

[英]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将检查其文件与否

Update Python 3.4+更新 Python 3.4+

Read all files读取所有文件

from pathlib import Path

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

Read all files filtered by extension读取按扩展名过滤的所有文件

from pathlib import Path

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

Read all files in directory tree filtered by extension读取按扩展名过滤的目录树中的所有文件

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")

Path.open()路径.open()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM