简体   繁体   English

将文件夹的文件夹中的文件重命名为其父文件夹?

[英]rename a files within a folder of a folder to its parent folder?

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我知道获取所有文件的基本 python 代码是这样的

  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.但是是否有python代码来更改要添加的文件的所有名称,至少在起始名称中包含父文件的日期。

thanks in advance!提前致谢!

Here is one-way using pathlib from python 3.4+ and f-strings from python 3.6+这是使用 python 3.4+ 中的 pathlib 和 python 3.6+ 中的 f-strings 的一种方法

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.首先,您需要在顶级目录中设置路径,以便我们可以递归查找所有 csv 文件并使用简单的 for 循环重命名。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM