python-3.x - 如何使用python重命名同一文件夹但不同子文件夹中不同格式的文件
问题描述
我有一种情况,我必须重命名文件夹中的文件。请找到场景,
例子 :
Elements(Main Folder)<br/>
2(subfolder-1) <br/>
sample_2_description.txt(filename1)<br/>
sample_2_video.avi(filename2)<br/>
3(subfolder2)
sample_3_tag.jpg(filename1)<br/>
sample_3_analysis.GIF(filename2)<br/>
sample_3_word.docx(filename3)<br/>
我想将文件的名称修改为,
Elements(Main Folder)<br/>
2(subfolder1)<br/>
description.txt(filename1)<br/>
video.avi(filename2)<br/>
3(subfolder2)
tag.jpg(filename1)<br/>
analysis.GIF(filename2)<br/>
word.docx(filename3)<br/>
有人可以指导如何编写代码吗?
解决方案
重命名文件的递归目录遍历可以基于这个答案。我们需要做的就是在接受的答案中替换文件名而不是扩展名。
这是一种方法 - 拆分文件名_
并使用拆分列表的最后一个索引作为新名称
import os
import sys
directory = os.path.dirname(os.path.realpath("/path/to/parent/folder")) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
for filename in files:
subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
filePath = os.path.join(subdirectoryPath, filename) #get the path to your file
newFilePath = filePath.split("_")[-1] #create the new name by splitting the old name by _ and grabbing last index
os.rename(filePath, newFilePath) #rename your file
希望这可以帮助。
推荐阅读
- java - 按下时如何全屏显示图像?
- ruby - storage-attach id 与 vagrant 自定义 id 不同
- scala - 如何将向量的列或序列转换为稀疏矩阵?
- javascript - 用于在 javascript 中录制视频的 Ziggeo 元配置文件参数
- c# - 时间:2019-04-01 标签:c#fizzbuzz自动数字生成器
- angular - 仅从模块材料中应用日期选择器年份修复
- python - 具有命名占位符替换的多行字符串格式
- python - FileToGoogleCloudStorageOperator 的替代方案
- memory - 进程之间的内存空间如何保持不同?
- ios - 删除 UITableView 部分中的所有内容后结束编辑