gpt4 book ai didi

python - 进入子文件夹(python)

转载 作者:行者123 更新时间:2023-12-01 05:10:42 24 4
gpt4 key购买 nike

我写了一些东西来删除文件名中的特殊字符。但它只包含一个文件夹,而不包含它的子文件夹。我怎样才能在子文件夹和子子文件夹等中执行此操作?

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它允许您浏览文件夹及其文件和子文件夹等,而不是 os.listdir

编辑您的代码,如下所示:

content = os.walk(directory)

for dirpath, dirnames, filenames in content:
for file in filenames:
dirfile = os.path.join(dirpath, file)

# The rest of your code

关于python - 进入子文件夹(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24301454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com