python对文件夹的操作汇总,方便查阅使用
文章目录
1、遍历指定目录,显示目录下的所有文件名2、遍历文件夹及其子文件夹的所有文件,获取文件的列表3、Python 遍历子文件和所有子文件夹 输出字符串4、对文件批量更名
1、遍历指定目录,显示目录下的所有文件名
import os
def fileInFolder(filepath
):
pathDir
= os
.listdir
(filepath
)
files
= []
for allDir
in pathDir
:
child
= os
.path
.join
('%s\\%s' % (filepath
, allDir
))
files
.append
(child
.decode
('gbk'))
return files
filepath
= "C:\\files"
print fileInFolder
(filepath
)
输出:
[u
'C:\\files\\a.txt', u
'C:\\files\\b.txt', u
'C:\\files\\c']
2、遍历文件夹及其子文件夹的所有文件,获取文件的列表
import os
def getfilelist(filepath
):
filelist
= os
.listdir
(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 遍历子文件和所有子文件夹 输出字符串
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、对文件批量更名
import os
def filesRename(filepath
):
filelist
= os
.listdir
(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
)
转载请注明原文地址:https://blackberry.8miu.com/read-26934.html