这是我第一次使用python,我总是遇到错误183。我创建的脚本在网络中搜索所有“.py”文件,并将它们复制到我的备份驱动器中。请不要嘲笑我的剧本,因为这是我的第一次。
有没有线索知道我在脚本中做错了什么?
import os
import shutil
import datetime
today = datetime.date.today()
rundate = today.strftime("%Y%m%d")
for root,dirr,filename in os.walk("p:\\"):
for files in filename:
if files.endswith(".py"):
sDir = os.path.join(root, files)
dDir = "B:\\Scripts\\20120124"
modname = rundate + '_' + files
shutil.copy(sDir, dDir)
os.rename(os.path.join(dDir, files), os.path.join(dDir, modname))
print "Renamed %s to %s in %s" % (files, modname, dDir)
发布于 2012-01-25 01:15:56
我猜你是在windows上运行脚本。根据the list of windows error codes,错误183为ERROR_ALREADY_EXISTS
所以我猜脚本失败是因为您试图重命名一个文件而不是现有的文件。
也许您每天运行该脚本不止一次?这将导致所有目标文件都已存在,因此当脚本再次运行时,重命名将失败。
如果您特别想覆盖这些文件,那么您可能应该首先使用os.unlink
删除它们。
发布于 2019-10-23 05:51:38
考虑到错误183是[Error 183] Cannot create a file when that file already exists
,你很可能会在os.walk()
调用中找到两个同名的文件,在第一个文件成功重命名后,第二个文件将无法重命名为相同的名称,所以你会得到一个文件已经存在的错误。
我建议在os.rename()
调用周围尝试/例外来处理这种情况(在名称后面附加一个数字或其他东西)。
是的,我知道这个问题已经被问了7年了,但如果我是通过谷歌搜索到这里的,也许其他人也会找到这个问题,这个答案可能会有所帮助。
发布于 2022-03-04 07:26:50
我只是遇到了同样的问题,当你试图重命名一个文件夹时,在同一目录下的文件夹具有相同的名称,Python将会抛出一个错误。
如果您尝试在Windows资源管理器中执行此操作,它将询问您是否要合并这两个文件夹。但是,Python没有这个特性。
下面是我的代码,目的是在已经存在相同名称的文件夹的情况下重命名文件夹,这实际上是合并文件夹。
import os, shutil
DEST = 'D:/dest/'
SRC = 'D:/src/'
for filename in os.listdir(SRC): # move files from SRC to DEST folder.
try:
shutil.move(SRC + filename, DEST)
# In case the file you're trying to move already has a copy in DEST folder.
except shutil.Error: # shutil.Error: Destination path 'D:/DEST/xxxx.xxx' already exists
pass
# Now delete the SRC folder.
# To delete a folder, you have to empty its files first.
if os.path.exists(SRC):
for i in os.listdir(SRC):
os.remove(os.path.join(SRC, i))
# delete the empty folder
os.rmdir(SRC)
https://stackoverflow.com/questions/8990725
复制相似问题