I’m trying to use a For loop in the code below to go through a list of files and rename them with the file directory’s name.
JavaScript
x
14
14
1
import re # add this to your other imports
2
import os
3
4
for files in os.walk("."):
5
for f_new in files:
6
folder = files.split(os.sep)[-2]
7
print(folder)
8
name_elements = re.findall(r'(Position)(d+)', f_new)[0]
9
name = name_elements[0] + str(int(name_elements[1]))
10
print(name) # just for demonstration
11
dst = folder + '_' + name
12
print(dst)
13
os.rename('Position014 (RGB rendering) - 1024 x 1024 x 1 x 1 - 3 ch (8 bits).tif', dst)
14
Advertisement
Answer
Use pathlib
Path.rglob
: This is like callingPath.glob()
with'**/'
added in front of the given relative pattern:.parent
or.parents[0]
: An immutable sequence providing access to the logical ancestors of the path- If yo want different parts of the path, index
parents[]
differentlyfile.parents[0].stem
returns'test1'
or'test2'
depending on the filefile.parents[1].stem
returns'photos'
file.parents[2].stem
returns'stack_overflow'
- If yo want different parts of the path, index
.stem
: The final path component, without its suffix.suffix
: The file extension of the final component.rename
: Rename this file or directory to the given target- The following code, finds only
.tiff
files. Use*.*
to get all files. - If you only want the first 10 characters of
file_name
:file_name = file_name[:10]
JavaScript
1
24
24
1
form pathlib import Path
2
3
# set path to files
4
p = Path('e:/PythonProjects/stack_overflow/photos/')
5
6
# get all files in subdirectories with a tiff extension
7
files = list(p.rglob('*.tiff'))
8
9
# print files example
10
[WindowsPath('e:/PythonProjects/stack_overflow/photos/test1/test.tiff'), WindowsPath('e:/PythonProjects/stack_overflow/photos/test2/test.tiff')]
11
12
# iterate through files
13
for file in files:
14
file_path = file.parent # get only path
15
dir_name = file.parent.stem # get the directory name
16
file_name = file.stem # get the file name
17
suffix = file.suffix # get the file extension
18
file_name_new = f'{dir_name}_{file_name}{suffix}' # make the new file name
19
file.rename(file_path / file_name_new) # rename the file
20
21
22
# output files renamed
23
[WindowsPath('e:/PythonProjects/stack_overflow/photos/test1/test1_test.tiff'), WindowsPath('e:/PythonProjects/stack_overflow/photos/test2/test2_test.tiff')]
24