2 回答
TA贡献1802条经验 获得超5个赞
import os
def list_files(dir):
sub_folders = os.listdir(dir)
for sub_folder in sub_folders:
sub_folder_path = os.path.join(dir,sub_folder)
for root, dirs, files in os.walk(sub_folder_path):
for file in files:
new_filename = root.replace(dir, "").replace(os.path.sep,"_").strip("_")+"_" + file
os.rename(os.path.join(root, file), os.path.join(root, new_filename))
input_dir = ""
assert os.path.isdir(input_dir),"Enter a valid directory path which consists of sub-directories"
list_files(input_dir)
这将为多个子目录而不是嵌套目录完成这项工作。如果要更改文件名的格式,请更改new_filename = sub_folder+ "" + file.
TA贡献1797条经验 获得超6个赞
它listdir()在两个级别都使用,它检查并忽略第一级子目录中更深的嵌套目录。
这是我的代码,注释很好:
import os
def collapse_dirs(dir):
# get a list of elements in the target directory
elems = os.listdir(dir)
# iterate over each element
for elem in elems:
# compute the path to the element
path = os.path.join(dir, elem)
# is it a directory? If so, process it...
if os.path.isdir(path):
# get all of the elements in the subdirectory
subelems = os.listdir(path)
# process each entry in this subdirectory...
for subelem in subelems:
# compute the full path to the element
filepath = os.path.join(path, subelem)
# we only want to proceed if the element is a file. If so...
if os.path.isfile(filepath):
# compute the new path for the file - I chose to separate the names with an underscore,
# but this line can easily be changed to use whatever separator you want (or none)
newpath = os.path.join(path, elem + '_' + subelem)
# rename the file
os.rename(filepath, newpath)
def main():
collapse_dirs('/tmp/filerename2')
main()
这是我在运行代码之前的目标目录:
filerename2
├── a
│ └── xxx.txt
├── b
│ ├── xxx.txt
│ └── yyyy
│ └── zzzz
├── c
│ └── xxx.txt
└── xxxx
这是之后:
filerename2
├── a
│ └── a_xxx.txt
├── b
│ ├── b_xxx.txt
│ └── yyyy
│ └── zzzz
├── c
│ └── c_xxx.txt
└── xxxx
添加回答
举报