Python-获取指定路径下的所有文件及文件名

import os
 import glob

**方法1:**os.walk(top, topdown=Ture, οnerrοr=None, followlinks=False) 通过该函数可以得到一个三元元组(dirpath, dirnames, filenames).dirpath:表示获取的目录的路径,以string形式返回值。dirnames: 包含了当前dirpath路径下所有的子目录名字(不包含目录路径),以列表形式返回值。filenames:包含了当前dirpath路径下所有的非目录子文件的名字(不包含目录路径)。返回指定路径下的子目录及文件及i子文件名,包含子目录。

path1 = r"C:\Users\11764\Desktop\Data"
 f = os.walk(path1)
 for dirpath,dirnames,filenames in f:
 print(dirpath)
 print(dirnames)
 print(filenames)output:
C:\Users\11764\Desktop\Data
 [‘2020-09-16’, ‘2020-10-11’]
 [‘baidu_index_0625.xlsx’, ‘city_id.xlsx’, ‘city_index_0625.xlsx’, ‘province_id.xlsx’, ‘province_index_0625.xlsx’]
 C:\Users\11764\Desktop\Data\2020-09-16
 []
 [‘2020_10_11drowplot.xlsx’, ‘DataAnalyst.csv’, ‘PCP V1 自动文库建库信息统计表-20200905.xlsx’]
 C:\Users\11764\Desktop\Data\2020-10-11
 []
 []

**方法二:**os.listdir( ) 函数得到的是仅当前路径下的文件名,不包括子目录中的文件,所有需要使用递归的方法得到全部文件名。#返回指定路径下的所有文件,不包含子目录。

path1 = r"C:\Users\11764\Desktop\Data"
 f = os.listdir(path1)
 print(f)output:
[‘2020-09-16’,
 ‘2020-10-11’,
 ‘baidu_index_0625.xlsx’,
 ‘city_id.xlsx’,
 ‘city_index_0625.xlsx’,
 ‘province_id.xlsx’,
 ‘province_index_0625.xlsx’]

其中os.path.splitext()函数将路径拆分为文件名+扩展名(后缀)。#返回指定路径下的,符合条件的文件名。

path1 = r"C:\Users\11764\Desktop\Data"
 file_f = glob.glob(path1+"\*.xlsx")
 file_foutput:
 [‘C:\Users\11764\Desktop\Data\baidu_index_0625.xlsx’,
 ‘C:\Users\11764\Desktop\Data\city_id.xlsx’,
 ‘C:\Users\11764\Desktop\Data\city_index_0625.xlsx’,
 ‘C:\Users\11764\Desktop\Data\province_id.xlsx’,
 ‘C:\Users\11764\Desktop\Data\province_index_0625.xlsx’]#将文件拆解成文件名+拓展名:
 os.path.splitext(file_f[0])output:
 (‘C:\Users\11764\Desktop\Data\baidu_index_0625’, ‘.xlsx’)

方法三: glob.glob( ) 该方法需要一个参数用来指定匹配的路径字符串(字符串可以为绝对路径也可以为相对路径),其返回的文件名只包括当前目录里的文件名,不包括子文件夹里的文件。
支持通配符操作,,?,[]这三个通配符,代表0个或多个字符,?代表一个字符,[]匹配指定范围内的字符,如[0-9]匹配数字。

path1 = r"C:\Users\11764\Desktop\Data"
 file = glob.glob(path1+"\"+"*.xlsx")
 fileoutput:
[‘C:\Users\11764\Desktop\Data\baidu_index_0625.xlsx’,
 ‘C:\Users\11764\Desktop\Data\city_id.xlsx’,
 ‘C:\Users\11764\Desktop\Data\city_index_0625.xlsx’,
 ‘C:\Users\11764\Desktop\Data\province_id.xlsx’,
 ‘C:\Users\11764\Desktop\Data\province_index_0625.xlsx’]


另外glob.iglob() 用法与glob.glob() 用法相似,唯一区别是glob.glob() 同时获取所有的匹配路径,而 glob.iglob一次只获取一个匹配路径。

path1 = r"C:\Users\11764\Desktop\Data"
 file = glob.iglob(path1+"\"+"*.xlsx")
 fileoutput:
<generator object _iglob at 0x0000022086999270>
#通过for循环对glob.iglob()对象进行遍历,可以输出该路径下的文件名。
 path1 = r"C:\Users\11764\Desktop\Data"
 file = glob.iglob(path1+"\"+"*.xlsx")
 file
 for i in file:
 print(i)output:
C:\Users\11764\Desktop\Data\baidu_index_0625.xlsx
 C:\Users\11764\Desktop\Data\city_id.xlsx
 C:\Users\11764\Desktop\Data\city_index_0625.xlsx
 C:\Users\11764\Desktop\Data\province_id.xlsx
 C:\Users\11764\Desktop\Data\province_index_0625.xlsx