Python:如何读取目录中的所有文件 [英] Python: How to read all files in a directory

查看:57
本文介绍了Python:如何读取目录中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这段代码可以读取特定文件的所有行.

I found this piece of code that reads all the lines of a specific file.

我如何编辑它,让它一一读取目录文件夹"中的所有文件(html、文本、php .etc),而不必指定每个文件的路径?我想在目录中的每个文件中搜索一个关键字.

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? 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') 将列出目录的所有内容
os.path.isfile 是否会检查它的文件

os.listdir('your_path') will list all content of a directory
os.path.isfile will check its file or not

这篇关于Python:如何读取目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆