Home > Backend Development > Python Tutorial > How to read the contents of a folder in python

How to read the contents of a folder in python

步履不停
Release: 2019-07-03 09:50:10
Original
7800 people have browsed it

How to read the contents of a folder in python

看thinking in java的时候发现有个题的答案不确定结果, 于是下载答案看下,结果是

How to read the contents of a folder in python

这个样子的,这样要怎么才能找到相对应的答案?于是我就着手写了一个快速遍历的脚本(我这里只是单纯的找了出来, 没有把找到的文件单独拿出来, 因为我的需求达到了,扩展项目是后来的人需要做的事情),话不多说,贴代码

#!/usr/bin/env python
# encoding: utf-8
'''
1、读取指定目录下的所有文件
2、读取文件,正则匹配出需要的内容,获取文件名
3、打开此文件(可以选择打开可以选择复制到别的地方去)
'''
import os.path
import re
 
 
# 遍历指定目录,显示目录下的所有文件名
def eachFile(filepath):
    pathDir =  os.listdir(filepath)
    for allDir in pathDir:
        child = os.path.join('%s\%s' % (filepath, allDir))
        if os.path.isfile(child):
            readFile(child)
#             print child.decode('gbk') # .decode('gbk')是解决中文显示乱码问题
            continue
        eachFile(child)
   
# 遍历出结果 返回文件的名字
def readFile(filenames):
        fopen = open(filenames, 'r') # r 代表read
        fileread = fopen.read()
        fopen.close()
        t=re.search(r'clearSpitValve',fileread)
        if t:
#             print "匹配到的文件是:"+filenames
            arr.append(filenames)       
 
if __name__ == "__main__":
    filenames = 'D:\java\\answer\\Thinking in Java4 Answer' # refer root dir
    arr=[]
    eachFile(filenames)
    for i in arr:
        print i
Copy after login

满足我的需求,需要做的事情 分3步

1、读取指定目录下的所有文件
2、读取文件,正则匹配出需要的内容,获取文件名
3、打开此文件<br><br> 相对于java来说 ,用python写的话能少写20行左右的代码,生产效率大大提高。人都舒服点
Copy after login

The above is the detailed content of How to read the contents of a folder in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template