Dav*_*ley 5 python rename batch-file
我想使用 python 重命名目录中的所有子文件夹。我认为这相当容易,但由于我是 Python 和编程的新手,所以我假设我错过了一些关键的东西。
这是我的文件夹结构:C:\Users\DBailey\Desktop\Here
- 此文件夹有两个文件夹:3303_InfigenSolar 和 3304_FurnaceCanyon
- 在这些文件夹中有 4 个其他子文件夹,在这些文件夹中有一堆文件。
我只想批量重命名3303_InfigenSolar和3304_FurnaceCanyon,以便它们读取3303_InfigenSolar_08315和3304_FurnaceCanyon_08315
到目前为止,这是我的代码:
now = datetime.datetime.now()
month = "0" + str(now.month)
day = now.day
year1 = str(now.year)
year2 = year1[2:]
date = str(month) + str(day) + str(year2)
newname = fn + "_" + str(date)
dir = 'C:\Users\DBailey\Desktop\Here'
folder = os.listdir(dir)
for fn in folder:
print newname
os.rename(fn, newname)
Run Code Online (Sandbox Code Playgroud)
当我运行脚本时 - 只打印一个文件夹(只有两个文件夹,但会添加更多文件夹)并且出现以下错误:
Traceback (most recent call last):
File "<interactive input>", line 2, in <module>
WindowsError: [Error 2] The system cannot find the file specified
Run Code Online (Sandbox Code Playgroud)
您需要os.path.join:
_dir = 'C:\Users\DBailey\Desktop\Here'
os.rename(os.path.join(_dir, fn), os.path.join(_dir,newname))
Run Code Online (Sandbox Code Playgroud)
python 正在您的 cwd 中查找fn
,您需要使用 join 告诉 python 该文件实际位于哪里,除非您的 cwd 实际上是该文件所在的目录。
如果您有多个目录要重命名,您还需要确保为循环中的每个目录创建唯一的名称。
dte = str(date)
for ind,fn in enumerate(folder,1):
os.rename(os.path.join(_dir, fn), os.path.join(_dir,"{}_{}".format(dte,ind)))
Run Code Online (Sandbox Code Playgroud)
您可以使用任何您想要的名称来区分文件夹名称,只需确保它们是唯一的即可。这还假设您只有目录,如果您有文件,那么您需要检查每个 fn 实际上是一个目录:
dte = str(date)
folder = (d for d in os.listdir(_dir))
for ind,fn in enumerate(folder,1):
p1 = os.path.join(_dir, fn)
if os.path.isdir(p1):
os.rename(p1, os.path.join(_dir,"{}_{}".format(dte,ind)))
Run Code Online (Sandbox Code Playgroud)