python常用代码和函数实例
来源:互联网 发布:吉他识谱软件 编辑:程序博客网 时间:2024/05/16 15:20
用python查找指定格式或名称的文件及修改指定文件夹名称
#-*- coding: GBK -*-import os, sys, renewdir = ""#递归搜索函数def search(rootdir,searchdirname): if os.path.isdir(rootdir): #print rootdir #分离路径和文件夹 split1 = os.path.split(rootdir) #print split1[1] #判断是否为指定的文件夹 if split1[1] == searchdirname: print "找到文件夹:%s" % (rootdir) try: #将文件夹名称改为新的文件夹名称 os.rename(rootdir,split1[0]+"\\"+newdir) print "文件夹 [%s] 已改名为 [%s]" % (rootdir,newdir) except: pass #遍历指定文件夹下的内容(文件和文件夹列表) listnew = os.listdir(rootdir) for l1 in listnew: path = rootdir + "\\" + l1 #递归调用 search(path,searchdirname) else: #print '不是文件夹:%s' % (rootdir) return #搜索指定格式的文件 def find_file_by_pattern(pattern,base): '''''查找给定文件夹下面所有 ''' re_file = re.compile(pattern) if base == ".": base = os.getcwd() final_file_list = [] #print base cur_list = os.listdir(base) for item in cur_list: print item full_path = os.path.join(base, item) if full_path.endswith(pattern):#不能写成单引号,单引号达不到预期的效果 # print full_path #bfile = os.path.isfile(item) if os.path.isfile(full_path): if re_file.search(full_path): print re_file.search(full_path).group() final_file_list.append(full_path) else: final_file_list += find_file_by_pattern(pattern,full_path) #for filename in re_file.findall(final_file_list): # print filename else: continue return final_file_listdef serchDir(startdir,dirname): search(startdir,dirname) if __name__ == '__main__': root=raw_input("输入搜索目录:") key=raw_input("输入待搜索的文件夹名称:") #newdir = raw_input("文件夹改名为:") #serchDir(root,key) base="".join([root,key]) fileName=raw_input("请输入要查找的文件名称或后缀名:") for result in find_file_by_pattern(fileName,base): print result
如果要查找指定名字的文件只需要将以下代码注释即可
if full_path.endswith(pattern):#不能写成单引号,单引号达不到预期的效果 ...... ...... ...... else: continue
0 0
- python常用代码和函数实例
- python常用函数使用方法实例
- python常用函数示例和knn分类的一个实例之海伦约会系统
- div style常用属性和实例代码
- div style常用属性和实例代码
- div style常用属性和实例代码
- mysql常用函数详解和实例
- Python中的比较和判断代码实例
- 常用的Python库和示例代码
- 常用的Python库和示例代码
- python常用随机函数及带权重随机实例
- [Python]python常用代码
- python:常用的time模块和函数
- python时间函数和常用格式化
- python时间函数和常用格式化
- python 字符串和编码常用函数
- Python常用的模块和函数
- python时间函数和常用格式化
- python设置proxy
- 21天概览Java面试知识之基础篇
- 深入浅出---unix多进程编程之wait()和waitpid()函数
- android阻塞对话框和非阻塞对话框
- 区分Bootstrps、Bagging与 Boosting
- python常用代码和函数实例
- 寻找最好的编程语言
- OBIEE去掉主页左边部分内容
- [LeetCode] 026. Remove Duplicates from Sorted Array (Easy) (C++/Java)
- spirntf,你知道多少?
- 解释器模式
- spring源码研究之IoC容器在web容器中初始化过程
- html 无序列表_有序列表_框架
- ShellExecute, WinExec, CreateProcess区别