[英]move a file to a folder and rename it if a file with the same name already exists
[英]Rename and Move file if destination path already exists?
我正在嘗試創建一個腳本,將所有圖片從我的下載文件夾移動到我的圖片文件夾。 我的腳本工作到此為止(移動文件),除非它嘗試移動目標文件夾中已經具有相同名稱的文件 - 就像打印屏幕一樣。 如果圖片中已經存在printscreen1.png,則不會移動文件。
對於這樣的文件,我想重命名文件並將日期或時間添加到文件名中,然后在不替換原始打印屏幕的情況下移動它,這樣我就可以保留所有打印屏幕以備將來使用。
import os
import shutil
import datetime
downloadsb = os.path.join('B:\\Downloads')
pictures = os.path.join('B:\\Pictures')
for f in os.listdir(downloadsb):
if f.endswith((".jpg", ".gif", ".jpeg", ".png", ".ico", ".psd", ".sfw", ".webp", ".pdd", ".psb", ".bmp", ".rle", ".dib", ".eps", ".iff", ".tdi", ".jpf",
".jpx", ".jp2", ".j2c", ".jxk", ".jpc", ".jps", ".mp0", ".pcx", ".pdp", ".raw", ".pxr", ".pns")):
shutil.move(os.path.join(downloadsb, f), pictures)
if os.path.isfile(f):
os.rename(f,f + "date")
這是我的錯誤信息:
raise Error, "Destination path '%s' already exists" % real_dst
shutil.Error: Destination path 'B:\Pictures\printscreen1.png' already exists
這就是我到目前為止所擁有的,我將不勝感激任何幫助或建議。 謝謝
有一個內置庫可以檢查文件是否是圖像。 此外,您需要遍歷目錄(文件夾)中的文件。 這樣的事情應該工作(未測試):
import os
import shutil
import datetime
import imghdr
downloadsb = os.path.join('B:\\Downloads')
pictures = os.path.join('B:\\Pictures')
files = os.listdir(downloadsb)
for f in files:
try:
imghdr.what(f)
dest_name = f
if os.path.exists( os.path.join(pictures, dest_name) ):
dest_name += datetime.datetime.now().strftime('%H%M%S')
shutil.move(os.path.join(downloadsb, f),
os.path.join(pictures, dest_name))
except Exception as e:
continue
為什么不在搬家前檢查一下。 像下面這樣
注意:當文件存在時,您可以進行不同類型的重命名。 我只是附加 _new (到擴展名)。 不完全是你想要的,但這應該給出一個想法
import os
import shutil
import datetime
import glob
downloadsb = os.path.join('src')
pictures = os.path.join('dst')
for f in glob.glob(downloadsb + '/*'):
if f.endswith(
(".jpg", ".gif", ".jpeg", ".png", ".ico", ".psd", ".sfw", ".webp", ".pdd", ".psb", ".bmp",
".rle", ".dib", ".eps", ".iff", ".tdi", ".jpf", ".jpx", ".jp2", ".j2c", ".jxk", ".jpc", ".jps",
".mp0", ".pcx", ".pdp", ".raw", ".pxr", ".pns")):
dstFile = os.path.join(pictures, os.path.split(f)[1])
if os.path.exists(dstFile):
# Do whatever you want to rename the file here
shutil.move(f, dstFile + '_new')
else:
shutil.move(f, dstFile)
跑步前
dst:
tmp.jpg
src:
tmp.jpg
運行后
dst:
tmp.jpg tmp.jpg_new
src:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.