我有一个包含多个子文件夹的文件夹,每个子文件夹中都有一个文件。我正在使用python进行操作,并希望使用 关联的子文件夹名称加上旧文件名来重命名该文件,以成为新文件名 。
我已经可以使用os.walk()
来获取子文件夹和文件名的列表,但是在更改文件名时遇到了问题。
def list_files(dir):
r = []
for root, dirs, files in os.walk(dir):
for name in files:
r.append(os.path.join(root, name))
os.rename(name, r)
我得到了错误:
TypeError:重命名:dst应该是字符串,字节或os.PathLike,而不是 列表
当我返回r时,我得到了根目录和文件名,但是无法更改文件名。感谢任何帮助。
答案 0 :(得分:2)
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
。
答案 1 :(得分:1)
这与@VkreddyKomatireddy的答案类似,但是它在两个级别上都使用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