Python中将文件复制到不存在的目录

2024-06-25 22:44:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个程序,复制foto并根据日期对它们进行重命名,我想自动将foto复制到给定的子文件夹中,例如“\…\2014-09-28\13:34.jpg”。复制到现有的文件夹工作得很好,但至少shutils copy2命令似乎不能动态创建那些不存在的子文件夹,也就是说,它会引发

IOError: [Errno 2] No such file or directory: 'C:\Users\Roman\Desktop\Foddos!\Tmp\2010-03\13 (0).jpg'

(请注意,2010-13子文件夹不存在)是否存在任何方法?在

附言:整个过程配合得很好操作系统重命名. 但是我不想移动我的文件(把它们复制到一个临时目录,而不是使用rename似乎是一个相当讨厌的解决办法)

PPS:我在Windows7上使用Python2.7.6


Tags: orno命令程序文件夹file重命名jpg
1条回答
网友
1楼 · 发布于 2024-06-25 22:44:59

简单的解决方案是首先检查目录是否存在os.path.isdir,如果没有创建它。在

if not os.path.isdir(os.path.join(parent, subdir)):
   os.mkdir(os.path.join(parent, subdir))

# Your normal method here

您也可以使用os.makedirs创建任何中间目录,但请注意,如果任何目录已经存在,此方法将引发异常:

Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. Raises an error exception if the leaf directory already exists or cannot be created. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.

相关问题 更多 >