[英]renaming files in a directory + subdirectories in python
我有一些文件在 python 脚本中使用。 最新的要求是我进入一个将放置文件的目录并通过在文件名的开头添加日期戳和项目名称来重命名所有文件,同时保留原始名称。
即 foo.txt 变为 2011-12-28_projectname_foo.txt
构建新标签很容易,只是重命名过程让我很头疼。
你可以发帖试试吗?
我认为你应该只需要在os.rename中使用os.walk 。
像这样的东西:
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))
我知道这是我的一个较旧的帖子,但看到它被如何被观看了很多次,我想我会发布我做了什么来解决这个问题。
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('.')]
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)
关心单个文件夹中是否有更多文件以及我们是否需要为文件提供增量值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.