问题
I have a batch of folders that have a name based on the date. Each folder has a folder where they have file names which are all the same.
Is there a way rename the files so they become unique based on the directory structure (which appears is the parent folder (the first folder) which is based on the date) that they are held within.
\user\date\1_2_2019\ABC\0001.csv -> abc_1_2_2019.csv
\user\date\1_3_2019\JKL\0001.csv -> JKL_1_3_2019.csv
\user\date\1_4_2019\XYZ\0001.csv -> XYZ_1_4_2019.csv
\user\date\1_5_2019\123\0001.csv -> 123_1_5_2019.csv
\user\date\1_6_2019\456\0001.csv -> 456_1_6_2019.csv
I know the basic python code to get to all the files is this
import os
for dirname, _, filenames in os.walk('\user\date'):
for filename in filenames:
print(os.path.join(dirname, filename))
But is there a python code to change all the names of the files to add at the very least have the date of the parent file in the beginning name.
thanks in advance!
回答1:
Here is one-way using pathlib from python 3.4+ and f-strings from python 3.6+
first you need to set your path at the top-level directory, so we can recursively find all the csv files and rename with a simple for loop.
from pathlib import Path
files = Path(r'C:\Users\datanovice\Documents\Excels').rglob('*.csv')
# remove 'r' string if you're on macos.
for file in files:
parent_1 = file.parent.name
parent_2 = file.parent.parent.name
file.rename(Path(file.parent,f"{parent_1}_{parent_2}{file.suffix}"))
print(f"{file.name} --> {parent_1}_{parent_2}{file.suffix}")
#1.csv --> ABC_1_2_2019.csv
#1.csv --> ABC_2_2_2019.csv
result
for f in files:
print(f)
C:\Users\datanovice\Documents\Excels\1_2_2019\ABC\1.csv
C:\Users\datanovice\Documents\Excels\2_2_2019\ABC\1.csv
#after
for f in files:
print(f)
C:\Users\datanovice\Documents\Excels\1_2_2019\ABC\ABC_1_2_2019.csv
C:\Users\datanovice\Documents\Excels\2_2_2019\ABC\ABC_2_2_2019.csv
来源:https://stackoverflow.com/questions/59724872/rename-a-files-within-a-folder-of-a-folder-to-its-parent-folder