根据我要创建文件夹的文件名的前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)
错误
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'
答案 0 :(得分:0)
您似乎正在尝试在C:\\temp\\Test\\F12
中打开filename
目录copy
。
否则,请检查您是否有权打开/阅读该文件。