python - How to rename subfolders by copying the name of the file in the subfolder?
问题描述
I'm trying to rename subfolders based on an a file name in the folder. I would like the folder name and file name to be the same. Currently I have a script that loops through all the subfolders and renames the files to the correct name. Now i need to take that "correct name" and rename the subfolder that file is in with the same name.
The current set up of the directory:
Folder A(Parent folder)
Folder sample1(Sub folder)
1. sample.pdf
2. correct_name1.xml
Folder B2(Sub folder)
1. sample.pdf
2. correct_name2.xml
Folder B3(Sub folder)
1. sample.pdf
2. correct_name3.xml
Expected output:
correct_name1 B1(Sub folder)
1. correct_name1.pdf
2. correct_name1.xml
correct_name2 B2(Sub folder)
1. correct_name2.pdf
2. correct_name2.xml
correct_name3 B3(Sub folder)
1. correct_name3.pdf
2. correct_name3.xml
Also if someone could help with renaming the pdf file as well that would be appreciated. The pdf file would be the exact same name as the xml.
I tried adding this inside the if statement, but it didn't rename the subfolders.
for dir in dirs:
sub_folder = os.path.join(path,curr_fld,dir)
print(sub_folder)
os.rename(sub_folder,new_name2)
My code:
def rename(path)
for root, dirs, files in os.walk(path):
for file in files:
curr_fld = os.path.basename(root)
old_name = os.path.join(path,curr_fld,file)
if file.endswith(".xml"):
file_name, file_ext = os.path.splitext(file)
print(file_name)
new_name = "{}-{}-{}-{}{}".format(cfr, year, title, item_id, file_ext) # this is what i had done originally to get the correct file name
new_name2 = os.path.join(path,curr_fld,new_name) #my correct name
try:
os.rename(old_name,new_name2)
except WindowsError:
print("Didn't work!")
解决方案
You should use root
as the directory to rename if the files
list contains an .xml
file:
def rename(path):
for root, _, files in os.walk(path):
try:
new_name, _ = next(os.path.splitext(file) for file in files if file.endswith('.xml'))
except StopIteration:
continue
os.rename(root, os.path.join(os.path.dirname(root), new_name))
推荐阅读
- html - 使用 Bootstrap 为面板标题中的按钮垂直居中对齐
- clojurescript - 使用 figwheel 从 clojurescript 编译生产资产
- c# - 如何将第二个 ItemCollection(可绑定)添加到 TreeViewItem?
- android - 启用通知后通信超时断开状态 8 (Android 7.1.2)
- mysql - 在MYSQL中将String(varchar)转换为毫秒
- python - 使循环有向图无环(需要解释)
- android - 如何在 Android Studio 中为 APK 构建获取正确的 gradle.startParameter.taskNames
- python - 在cmd中编译我的python代码时遇到了这个问题
- python-3.x - 如何从字符串创建嵌套字典
- python - 将两个数据框相乘 Python