这是我的第一个 python 脚本之一,旨在进入一个目录并将某个扩展名的所有文件重命名为相同的东西。例如,进入音乐目录,将所有专辑封面文件的名称更改为 folder.jpg 之类的名称,以便 foobar2000 等音乐播放软件轻松识别和显示。
我目前收到标题中的错误。我试过了:
os.chmod(pathname, 0777)
和
os.chmod(pathname, stat.S_IWOTH)
允许其他实体编辑我正在查看的目录,但错误仍然存在。我对 Windows 的权限系统或 Python 不太熟悉,所以这让我很困惑。知道我哪里出错了吗?
#Changes file names in every subdirectory of the target directory
import os
import sys
import shutil
#Get target path
pathname = raw_input('Enter path for music directory (ex. C:\\Music): ')
try:
os.chdir(pathname)
except:
print('Failed. Invalid directory?')
sys.exit()
#Get variables for renaming
fn = raw_input('Enter desired file name for all converted files: ')
ft = raw_input('Enter the file extension you want the program to look for (ex. .jpg): ')
outname = fn + ft
#Create path tree
for path, subdirs, files in os.walk (pathname):
#Search tree for files with defined extention
for name in files:
if name.lower().endswith(ft):
#Rename the files
src = os.path.join(path, name)
print (src)
dst = os.path.join(path, outname)
print dst
shutil.move(src, dst)
print('Complete')
第二个更良性的问题是,当我使用打印语句检查正在编辑的文件时,似乎在尝试第一个 .jpg 之前,程序处理并重命名了一个名为 d:\test\folder.jpg 的文件不存在。这似乎成功了,当处理现有文件时,程序第二次在最后一个循环中失败。程序运行如下:
>>> ================================ RESTART ================================
>>>
Enter path for music directory (ex. C:\Music): d:\test
Enter desired file name for all converted files: folder
Enter the file extension you want the program to look for (ex. .jpg): .jpg
d:\test\folder.jpg
d:\test\folder.jpg
d:\test\Anathema\Alternative 4\AA.jpg
d:\test\Anathema\Alternative 4\folder.jpg
Traceback (most recent call last):
File "D:\Documents\Programming\Python scripts\Actually useful\bulk_filename_changer.py", line 29, in <module>
shutil.move(src, dst)
File "C:\Python27\lib\shutil.py", line 301, in move
copy2(src, real_dst)
File "C:\Python27\lib\shutil.py", line 130, in copy2
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 83, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'd:\\test\\Anathema\\Alternative 4\\folder.jpg'
>>>
该故障似乎是良性的,因为它不会导致错误,但它可能与我在处理第一个“真实”文件时导致出现 IOError 的代码中的错误有关。打败我...