在Python中重命名目录及子目录中的文件

3 投票
3 回答
3676 浏览
提问于 2025-04-17 09:11

我在写一个Python脚本,正在处理一些文件。最近的要求是,我需要进入一个文件夹,把里面的所有文件重命名,方法是给每个文件名的开头加上日期和项目名称,同时保留原来的文件名。

比如说,foo.txt 就变成了 2011-12-28_projectname_foo.txt。

生成这个新名字其实很简单,问题在于重命名的过程让我有点困惑。

3 个回答

1
import os

dir_name = os.path.realpath('ur directory')

cnt=0  for root, dirs, files in os.walk(dir_name, topdown=False):
    for file in files:
        cnt=cnt+1
        file_name = os.path.splitext(file)[0]#file name no ext
        extension = os.path.splitext(file)[1]
        dir_name = os.path.basename(root)
        try: 
            os.rename(root+"/"+file,root+"/"+dir_name+extension)
        except FileExistsError: 
            os.rename(root+"/"+file,root+""+dir_name+str(cnt)+extension)

要考虑一个文件夹里是否有更多的文件,以及我们是否需要给这些文件的名字加上递增的数字。

7

你能把你尝试过的内容发出来吗?

我觉得你只需要用一下 os.walkos.rename 就可以了。

大概可以这样写:

import os
from os.path import join

for root, dirs, files in os.walk('path/to/dir'):
    for name in files:
        newname = foo + name
        os.rename(join(root,name),join(root,newname))
1

我知道这是我以前的一个帖子,不过因为这个帖子被看了很多次,我想把我解决这个问题的方法分享出来。

import os

sv_name="(whatever it's named)"
today=datetime.date.today()
survey=sv_name.replace(" ","_")
date=str(today).replace(" ","_")
namedate=survey+str(date)

[os.rename(f,str(namedate+"_"+f)) for f in os.listdir('.') if not f.startswith('.')]

撰写回答