0
基于文件名的前3个字符我想创建一个文件夹,然后复制到相关文件中。基于文件名复制多文件
我有一个脚本可以在第一时间运行,但是如果我多次运行它,我会得到一个错误 我相信我需要检查文件是否先存在,但是我一直无法得到它的工作。 或者从os.list
任何帮助将不胜感激过滤掉新创建的文件夹:
srcpath = 'C:\\temp\\Test'
srcfiles = os.listdir(srcpath)
destpath = 'C:\\temp\\Test'
# extract the three letters from filenames
destdirs = list(set([filename[0:3] for filename in srcfiles]))
def create(destdirs, destpath):
full_path = os.path.join(destpath, destdirs)
if not os.path.exists(full_path):
os.mkdir(full_path)
return full_path
def copy(filename, dirpath):
shutil.copy(os.path.join(srcpath, filename), dirpath)
# create destination directories and store their names along with full paths
targets = [
(folder, create(folder, destpath)) for folder in destdirs
]
for destdirs, full_path in targets:
for filename in srcfiles:
if destdirs == filename[0:3]:
copy(filename, full_path)
ERROR
Traceback (most recent call last):
File "C:/Users/Desktop/copy_only.py", line 45, in <module>
copy(filename, full_path)
File "C:/Users/Desktop/copy_only.py", line 35, in copy
shutil.copy(os.path.join(srcpath, filename), dirpath)
File "C:\Python27\lib\shutil.py", line 119, in copy
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 13] Permission denied: 'C:\\temp\\Test\\F12'
正确它试图打开F12作为文件名。这就是为什么我想过滤掉listdir中的文件夹。导演是在本地计算机上将充分的权利,所以我不相信这是一个权限问题 – Adam