我的github
posts - 3243,  comments - 42,  views - 158万

遍历文件夹下的文件名

参考:https://blog.csdn.net/qingjiu3/article/details/122986159

import os
path='d:/test'
try:
  path=unicode(path,'utf-8')#经过编码处理
except:
  pass#python3已经移除unicode,而且默认是utf8编码,所以不用转os.listdir(path)

参考:http://www.viiis.cn/news/show_86068.html

UnicodeDecodeError: 'utf8' codec can't decode byte 0xca in position 2: invalid continuation byte

解决方法:
三种方法均可以!

1、将 encoding=’utf-8’ 改为GB2312、gbk、ISO-8859-1,随便尝试一个均可以!

f = open('txt01.txt',encoding='utf-8')

参考:https://blog.csdn.net/sunflower_sara/article/details/103957385

之所以这么麻烦是因为我的pycharm是用的arcgis自带的python2.7版本。。

复制代码
#导入OS模块
import os
#待搜索的目录路径
path = "D:\dataset"
#待搜索的名称
filename = "123"
#定义保存结果的数组
result = []

def findfiles(path):
    # 首先遍历当前目录所有文件及文件夹
    file_list = os.listdir(path)
    # 循环判断每个元素是否是文件夹还是文件,是文件夹的话,递归
    for file in file_list:
        # 利用os.path.join()方法取得路径全名,并存入cur_path变量,否则每次只能遍历一层目录
        cur_path = os.path.join(path, file)
        # 判断是否是文件夹
        if os.path.isdir(cur_path):
            findfiles(cur_path)
        else:
            # 判断是否是特定文件名称
            if filename in file:
                result.append(file)


if __name__ == '__main__':
    findfiles(path)
    print(result)
复制代码

 

posted on   XiaoNiuFeiTian  阅读(547)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2021-09-14 Vue自定义树状列表选择或数据展示(树状菜单)
2021-09-14 tree-store.js树存储
2021-09-14 element-ui:el-tree-node
2021-09-14 Cesium打包
2021-09-14 Cesium:An erron occurred while rendering. Rendering has stopped. SecurityError: Failed to construct Worker'
2021-09-14 webpack打包之后index.html空白
2018-09-14 香农小波
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示