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

WindowsError: [Error 183] Cannot create a file when that file already exists

What fix should I make?

解决方案

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值