python对文件夹的操作汇总,方便查阅使用
1、遍历指定目录,显示目录下的所有文件名
#-*- coding:utf-8 -*- import os def fileInFolder(filepath): pathDir = os.listdir(filepath) # 获取filepath文件夹下的所有的文件 files = [] for allDir in pathDir: child = os.path.join(‘%s\\%s‘ % (filepath, allDir)) files.append(child.decode(‘gbk‘)) # .decode(‘gbk‘)是解决中文显示乱码问题 # print child # if os.path.isdir(child): # print child # simplepath = os.path.split(child) # print simplepath return files filepath = "C:\\files" print fileInFolder(filepath) 输出: [u‘C:\\files\\a.txt‘, u‘C:\\files\\b.txt‘, u‘C:\\files\\c‘]
2、遍历文件夹及其子文件夹的所有文件,获取文件的列表
#-*- coding:utf-8 -*- import os def getfilelist(filepath): filelist = os.listdir(filepath) # 获取filepath文件夹下的所有的文件 files = [] for i in range(len(filelist)): child = os.path.join(‘%s\\%s‘ % (filepath, filelist[i])) if os.path.isdir(child): files.extend(getfilelist(child)) else: files.append(child) return files filepath = "C:\\files" print getfilelist(filepath) 输出: [‘C:\\files\\a.txt‘, ‘C:\\files\\b.txt‘, ‘C:\\files\\c\\d.txt‘, ‘C:\\files\\c\\e.txt‘, ‘C:\\files\\c\\f\\g.txt‘]
3、Python 遍历子文件和所有子文件夹 输出字符串
参考: http://blog.csdn.net/Qian_F/article/details/9896283
#-*- coding:utf-8 -*- import os def getfilelist(filepath, tabnum=1): simplepath = os.path.split(filepath)[1] returnstr = simplepath+"目录<>"+"\n" returndirstr = "" returnfilestr = "" filelist = os.listdir(filepath) for num in range(len(filelist)): filename=filelist[num] if os.path.isdir(filepath+"/"+filename): returndirstr += "\t"*tabnum+getfilelist(filepath+"/"+filename, tabnum+1) else: returnfilestr += "\t"*tabnum+filename+"\n" returnstr += returnfilestr+returndirstr return returnstr+"\t"*tabnum+"</>\n" filepath = "C:\\files" f = open("test.xml","w+") f.writelines(getfilelist(filepath)) f.close()
4、对文件批量更名
#-*- coding:utf-8 -*- import os def filesRename(filepath): filelist = os.listdir(filepath) # 获取filepath文件夹下的所有的文件 files = [] for i in range(len(filelist)): child = os.path.join(‘%s\\%s‘ % (filepath, filelist[i])) if os.path.isdir(child): continue else: newName = os.path.join(‘%s\\%s‘ % (filepath, str(i) + "_" + filelist[i])) print newName os.rename(child, newName) filepath = "C:\\files2" filesRename(filepath)
时间: 2024-10-12 03:39:42