python遍历目录下所有文件_用Python遍历指定文件夹下所有文件

使用 Python 遍历文件非常简单,核心函数是使用 os.walk(folder) 函数,folder就是你想要搜索的文件夹的最顶层。

例如,我们有一个文件夹叫 base/ :

base/

├── fileA.txt

├── fileA2.xls

├── fileA3.xls

├── fileA4.pdf

├── sub1

│ ├── fileB.txt

│ ├── fileB2.xls

│ └── fileB3.pdf

└── sub2

├── fileB.txt

├── fileC2.xls

└── fileC3.pdf

base/ 文件夹下面有4个文件("fileA.txt", "fileA2.xls", "fileA3.xls", "fileA4.pdf")和两个文件夹(sub1/ 和 sub2/)。sub1/ 文件夹里面有3个文件("fileB.txt", "fileB2.xls", "fileB3.pdf"),sub2/ 文件夹你们也有3个文件("fileB.txt", "fileC2.xls", "fileC3.pdf")。注意,文件 "fileB.txt" 出现了两次,但是在不同的文件夹中。

现在我们想罗列出来这里面都有哪些文件,如何实现?

迭代生成 base 文件夹下所有的文件的名称:

def findAllFile(base):

for root, ds, fs in os.walk(base):

for f in fs:

yield f

我们可以在 base/ 文件夹同级的位置写个脚本测试一下:

# file: all_file.py

import os

def findAllFile(base):

for root, ds, fs in os.walk(base):

for f in fs:

yield f

def main():

base = './base/'

for i in findAllFile(base):

print(i)

if __name__ == '__main__':

main()

运行效果:

$ python all_file.py

fileA.txt

fileA2.xls

fileA3.xls

fileA4.pdf

fileB3.pdf

fileB.txt

fileB2.xls

fileC.txt

fileC3.pdf

fileC2.xls

到这一步,其实并没有什么用处,因为这里没有文件对应的路径信息。也就是说,如果你想打开文件的话,程序是找不到的,所以需要加上路径,使用的函数就是 os.path.join(),如下所示 :

def findAllFile(base):

for root, ds, fs in os.walk(base):

for f in fs:

fullname = os.path.join(root, f)

yield fullname

运行效果:

$ python all_file.py

./base/fileA.txt

./base/fileA2.xls

./base/fileA3.xls

./base/fileA4.pdf

./base/sub1/fileB3.pdf

./base/sub1/fileB.txt

./base/sub1/fileB2.xls

./base/sub2/fileC.txt

./base/sub2/fileC3.pdf

./base/sub2/fileC2.xls

接下来你就可以随心所欲的在脚本里操作文件啦。

比如,我想找出所有的 Excel 文件(后缀名 .xls):

# file: all_file.py

import os

def findAllFile(base):

for root, ds, fs in os.walk(base):

for f in fs:

if f.endswith('.xls'):

fullname = os.path.join(root, f)

yield fullname

def main():

base = './base/'

for i in findAllFile(base):

print(i)

if __name__ == '__main__':

main()

运行结果:

$ python all_file.py

./base/fileA2.xls

./base/fileA3.xls

./base/sub1/fileB2.xls

./base/sub2/fileC2.xls

如果你想要更加复杂的文件名匹配方案,使用正则表达式会比较方便,导入 re 模块即可。文件名在程序中可以被当成字符串对象来处理,很方便。

比如,有一个需求,需要找出 base/ 文件夹下所有文件名中包含数字的文件(囧。。。我也不知道为什么有这么奇葩的需求):

# file: all_file.py

import os, re

def findAllFile(base):

for root, ds, fs in os.walk(base):

for f in fs:

if re.match(r'.*\d.*', f):

fullname = os.path.join(root, f)

yield fullname

def main():

base = './base/'

for i in findAllFile(base):

print(i)

if __name__ == '__main__':

main()

执行效果:

$ python all_file.py

./base/fileA2.xls

./base/fileA3.xls

./base/fileA4.pdf

./base/sub1/fileB3.pdf

./base/sub1/fileB2.xls

./base/sub2/fileC3.pdf

./base/sub2/fileC2.xls

—— 完 2019-12-19 ——

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值