我正在尝试在下面的代码中使用 For 循环来浏览文件列表并使用文件目录的名称重命名它们。
import re # add this to your other imports
import os
for files in os.walk("."):
for f_new in files:
folder = files.split(os.sep)[-2]
print(folder)
name_elements = re.findall(r'(Position)(\d+)', f_new)[0]
name = name_elements[0] + str(int(name_elements[1]))
print(name) # just for demonstration
dst = folder + '_' + name
print(dst)
os.rename('Position014 (RGB rendering) - 1024 x 1024 x 1 x 1 - 3 ch (8 bits).tif', dst)
pathlib
Path.rglob
:这是像调用Path.glob()
与'**/'
在给定的相对图案前面加:.parent
或.parents[0]
:提供对路径逻辑祖先的访问的不可变序列
parents[]
不同的 索引
file.parents[0].stem
返回'test1'
或'test2'
取决于文件file.parents[1].stem
返回 'photos'
file.parents[2].stem
返回 'stack_overflow'
.stem
: 最后的路径组件,没有后缀.suffix
: 最终组件的文件扩展名.rename
: 将此文件或目录重命名为给定的目标.tiff
文件。使用*.*
得到的所有文件。file_name
:
file_name = file_name[:10]
form pathlib import Path
# set path to files
p = Path('e:/PythonProjects/stack_overflow/photos/')
# get all files in subdirectories with a tiff extension
files = list(p.rglob('*.tiff'))
# print files example
[WindowsPath('e:/PythonProjects/stack_overflow/photos/test1/test.tiff'), WindowsPath('e:/PythonProjects/stack_overflow/photos/test2/test.tiff')]
# iterate through files
for file in files:
file_path = file.parent # get only path
dir_name = file.parent.stem # get the directory name
file_name = file.stem # get the file name
suffix = file.suffix # get the file extension
file_name_new = f'{dir_name}_{file_name}{suffix}' # make the new file name
file.rename(file_path / file_name_new) # rename the file
# output files renamed
[WindowsPath('e:/PythonProjects/stack_overflow/photos/test1/test1_test.tiff'), WindowsPath('e:/PythonProjects/stack_overflow/photos/test2/test2_test.tiff')]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句