rename a files within a folder of a folder to its parent folder?

て烟熏妆下的殇ゞ 提交于 2021-01-04 09:23:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!