我的github

遍历文件夹下的文件名

参考: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 2022-09-14 10:40  XiaoNiuFeiTian  阅读(565)  评论(0)    收藏  举报