[英]how to rename files to sub directory
我正在尝试使用存在子目录的标签将子目录中的所有.wav文件重命名。Fox示例directory / sub-directory1 / 1_1.wav到directory / sub-directory1 / sdir1_1.wav 。 我知道如何在python中重命名文件,但无法遍历子目录,然后添加标签。 尽管下面的代码可用于对齐子目录和文件,但是它不会循环遍历所有文件,因为for dire in dirs:
如果文件大于Dirs,将无法工作
import os
rootdir = r'C:\Users\test'
for subdir, dirs, files in os.walk(rootdir):
for dire in dirs:
for file in files:
filepath = subdir+os.sep+file
if filepath.endswith('.wav'):
print (dire+ file)
我已经对此进行了测试,并且有效。
import shutil
import os
from glob import glob
# Define your source folder.
source_dir = 'F:\\Test\\in\\'
# Define your target folder.
target_dir = 'F:\\Test\\out\\'
# Define the file extension you want to search for.
file_ext = '*.mp4'
# use glob to create a list of files in your source DIR with teh desired extension.
file_check = glob(source_dir + file_ext)
# For each item in file_check shuttle will copy teh source file and write it renamed to your target location.
for i in file_check:
shutil.copy(i, target_dir + 'dir_out_' + os.path.basename(i))
#os.path.basename gives us just the filename and extension minus the absolute path.
#i,e test123456.mp4
以下是目标目录的内容:
F:\Test\out\dir_out_test_10.mp4
F:\Test\out\dir_out_test_2.mp4
F:\Test\out\dir_out_test_3.mp4
F:\Test\out\dir_out_test_4.mp4
F:\Test\out\dir_out_test_5.mp4
F:\Test\out\dir_out_test_6.mp4
F:\Test\out\dir_out_test_7.mp4
F:\Test\out\dir_out_test_8.mp4
F:\Test\out\dir_out_test_9.mp4
如果要执行文件系统移动而不是复制操作 ,请检出shutil和glob ,请使用shutil.move()
而不是shutil.copy()
。
编辑:
Python 3.5+
以下是在根目录DIR中查找所有文件的方法:
glob('F:\\test\\**\\*.mp4', recursive=True)
这将在根DIR和子文件夹中找到所有文件,然后可以使用上面的shutil方法对它们进行所需的处理。
经过一番反复尝试后,我得以实现结果。
import os
rootdir = r'C:\Users\test'
for dirpath, dirnames, filenames in os.walk(rootdir):
for file in filenames:
filepath = dirpath +os.sep+file
if filepath.endswith('wav'):
# split directory filepath
split_dirpath = dirpath.split(os.sep)
# take the name of the last directory which I want to tag
dir_tag = (split_dirpath[-1])
# wasn't necessary to split the extension, still....
f_name, f_ext = (os.path.splitext(file))
# add the tag of the sub dir
f_name= dir_tag +'_'+ f_name
# create the new file name
new_name = f_name +f_ext
print(new_name)
os.rename(filepath,dirpath+os.sep+new_name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.