重命名一个文件夹的文件夹中的文件到其父文件夹? [英] rename a files within a folder of a folder to its parent folder?

查看:93
本文介绍了重命名一个文件夹的文件夹中的文件到其父文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一批文件夹,它们的名称基于日期.每个文件夹都有一个文件夹,这些文件夹的文件名都相同.

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

我知道要获取所有文件的基本python代码是这个

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))

但是是否有Python代码可以更改要添加的文件的所有名称,至少要在其起始名称中添加父文件的日期.

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 3.4+版本的pathlib和python 3.6+版本的f-strings的一种方法.

Here is one-way using pathlib from python 3.4+ and f-strings from python 3.6+

首先,您需要在顶级目录中设置路径,以便我们可以递归地找到所有csv文件,并使用简单的for循环进行重命名.

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


结果

文件中f的

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

这篇关于重命名一个文件夹的文件夹中的文件到其父文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆