网络编程
位置:首页>> 网络编程>> Python编程>> Python os和os.path模块详情

Python os和os.path模块详情

作者:bingbangx  发布时间:2022-12-08 12:53:45 

标签:Python,os,os.path

1、目的:在Python中实现只读取扩展名为xlsx的文件

解决方法:

使用os模块。

Python os和os.path模块详情

解决思路:

  • 1、确定目录

  • 2、循环遍历每一个文件

  • 3、筛选符合条件的文件,读取数据

具体代码如下:

import os
# 1、首先定义路径
filepath = 'E:/old/工作/数据库表'
# 2、循环遍历路径下的每一个文件
for filename in os.listdir(filepath):
    # 3、列出文件中以.xlsx结尾的文件
    if filename.endswith(('.xlsx')):
        print(filename)

结果如下:

Python os和os.path模块详情

2、目的:使用Python来遍历指定目录下下各个文件夹中的文件

解决方法:

使用os.path模块的join方法

Python os和os.path模块详情

解决思路:

  • 1、定义一个函数,使用这个函数循环遍历,指定目录下的所有子文件夹

  • 2、调用函数,查看所有文件

具体代码:

def get_filelist(dir,Filelist):
    if os.path.isfile(dir): #判断path是否为文件
        Filelist.append(dir) # 将路径添加到列表中
    elif os.path.isdir(dir): #判断路径是否为目录
        for s in os.listdir(dir):  #遍历目录下的每一个文件
            new_dir = os.path.join(dir,s)
            get_filelist(new_dir,Filelist) #调用定义的函数
    return Filelist
 
list_ = get_filelist('E:/old/工作/数据库表',[])
print(len(list_))
for l in list_:
    print(l)

结果如下:

Python os和os.path模块详情

来源:https://blog.csdn.net/bingbangx/article/details/123871423

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com