Python程序在覆盖文件名(如果已经存在)的同时重命名文件名 [英] Python program to rename file names while overwriting if there already is that file

查看:932
本文介绍了Python程序在覆盖文件名(如果已经存在)的同时重命名文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我想要一个可更改文件名的python程序,但如果已有的文件具有该目标名称,我想覆盖它.

As the title says, I wanted a python program that changes the file name, but I wanted to overwrite if there already is a file with that destination name.

import os, sys

original = sys.argv[1]
output = sys.argv[2]

os.rename(original, output)

但是当已经有该目标名称的文件时,我的代码仅向我显示此错误.

But my code just shows me this error when there already is file with that destination name.

  os.rename<original, output>
WindowsError: [Error 183] Cannot create a file when that file already exists

我应该怎么做?

推荐答案

在Windows上,os.rename不会替换目标文件(如果存在).您必须先将其删除.您可以捕获该错误,然后在删除文件后重试:

On Windows os.rename won't replace the destination file if it exists. You have to remove it first. You can catch the error and try again after removing the file:

import os

original = sys.argv[1]
output = sys.argv[2]

try:
    os.rename(original, output)
except WindowsError:
    os.remove(output)
    os.rename(original, output)

这篇关于Python程序在覆盖文件名(如果已经存在)的同时重命名文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆