我寫了一些東西去除文件名中的特殊字符。但它只包含一個文件夾,而不是它的子文件夾。我如何在子文件夾和子文件夾等中執行此操作?進入子文件夾(python)
import os
import re
def dir_list2(directory, *args):
fileList = []
content = os.listdir(directory)
for file in content :
dirfile = os.path.join(directory, file)
if os.path.isfile(dirfile):
if len(args) == 0:
fileList.append(dirfile)
else:
if os.path.splitext(dirfile)[1][1:] in args:
fileList.append(dirfile)
print "##################################################"
print "Old filename:", file
filename = file
remove = re.compile("[^.a-zA-z0-9_]")
output = remove.sub('_', filename)
newfile = directory + "/" + output
os.rename(dirfile, newfile)
print "Corrected filename:", output
#Removes Special Characters
return fileList
if __name__ == '__main__':
fileList = dir_list2('/path/')
您可能需要使用[os.walk(https://docs.python.org/2/library/os.html#os.walk)而不是'os.listdir' – J0HN