Python 递归地复制和重命名文件会起作用,然后意外停止 上下文
需要重复复制和重命名图像文件,直到达到某个计数数Python 递归地复制和重命名文件会起作用,然后意外停止 上下文,python,python-3.x,loops,file-rename,file-copying,Python,Python 3.x,Loops,File Rename,File Copying,需要重复复制和重命名图像文件,直到达到某个计数数 更名部分必须满足一定的增长步骤 它是Python3.7.0 代码 输出 期望图像具有顺序编号的名称(即image1.jpg image5.jpg image9.jpg等) 问题 代码直到IMAGE.9JPG工作,然后在回溯中途停止:错误: Traceback (most recent call last): File "D:\home\user\main.py", line 17, in <module>
代码直到IMAGE.9JPG工作,然后在回溯中途停止:错误:
Traceback (most recent call last):
File "D:\home\user\main.py", line 17, in <module>
os.rename(os.path.join(dest,filename), os.path.join(dest,'captured'+ str(i) + '.jpg'))
FileExistsError: [WinError 183] Cannot create a file when that file already exists: './dst/image5.jpg' -> './dst/image9.jpg'
回溯(最近一次呼叫最后一次):
文件“D:\home\user\main.py”,第17行,在
重命名(os.path.join(dest,文件名),os.path.join(dest,'captured'+str(i)+'.jpg'))
FileExistError:[WinError 183]无法创建已存在的文件:'./dst/image5.jpg'->'./dst/image9.jpg'
如何改进代码?据我所知,您有一个问题,因为图像不是从0开始计数的,所以您应该检查最后一个编号的图像,获取其名称,从该图像获取其编号,然后继续从该编号重命名。问题在内部for循环中。您获取每个文件并尝试将其重命名为相同的文件名。@ack循环的
str(i)
不应该已经处理了吗?在os.listdir(dest)的文件名中:
循环i
不会更改。
Traceback (most recent call last):
File "D:\home\user\main.py", line 17, in <module>
os.rename(os.path.join(dest,filename), os.path.join(dest,'captured'+ str(i) + '.jpg'))
FileExistsError: [WinError 183] Cannot create a file when that file already exists: './dst/image5.jpg' -> './dst/image9.jpg'