简体   繁体   English

如果目标路径已存在,则重命名和移动文件?

[英]Rename and Move file if destination path already exists?

I am trying to create a script that moves all pictures from my downloads folder, to my pictures folder.我正在尝试创建一个脚本,将所有图片从我的下载文件夹移动到我的图片文件夹。 My script works this far (moving the files over), except when it tries to move a file that already has the same name in the destination folder - like with printscreens.我的脚本工作到此为止(移动文件),除非它尝试移动目标文件夹中已经具有相同名称的文件 - 就像打印屏幕一样。 It will not move the file if printscreen1.png already exists in pictures.如果图片中已经存在printscreen1.png,则不会移动文件。

For files like this, I would like to rename the file and add the date or time to the file name, then move it without replacing the original printscreen so I can keep both and all printscreens going toward the future.对于这样的文件,我想重命名文件并将日期或时间添加到文件名中,然后在不替换原始打印屏幕的情况下移动它,这样我就可以保留所有打印屏幕以备将来使用。

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")

Here is my error message:这是我的错误信息:

raise Error, "Destination path '%s' already exists" % real_dst
shutil.Error: Destination path 'B:\Pictures\printscreen1.png' already exists

This is what I have so far, I would appreciate any help or advice.这就是我到目前为止所拥有的,我将不胜感激任何帮助或建议。 Thank you谢谢

There's a built-in library that checks to see if a file is an image.有一个内置库可以检查文件是否是图像。 Also, you need to iterate over the files in the directory (folder).此外,您需要遍历目录(文件夹)中的文件。 Something like this should work (not tested):这样的事情应该工作(未测试):

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

Why not check it before moving.为什么不在搬家前检查一下。 Something like below像下面这样

NOTE: When the file exists you can do different types of renaming.注意:当文件存在时,您可以进行不同类型的重命名。 I and just appending _new (to the extension).我只是附加 _new (到扩展名)。 Not quite what you wanted but that should give an idea不完全是你想要的,但这应该给出一个想法

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)

Before running跑步前

dst:
tmp.jpg

src:
tmp.jpg

After running运行后

dst:
tmp.jpg  tmp.jpg_new

src:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果已存在同名文件,则将文件移动到文件夹并重命名 - move a file to a folder and rename it if a file with the same name already exists 重命名一个已经存在的文件 - Rename a file that already exists 如果文件已经存在,如何迭代地重命名文件(Python) - How to iteratively rename a file if it already exists (Python) 致命:目标路径“ myproject”已存在,并且不是空目录 - fatal: destination path 'myproject' already exists and is not an empty directory 如果目标文件夹中已存在文件,如何替换文件? - How can I replace a file if already exists in the destination folder? 将文件移动到文件夹或进行重命名的副本(如果目标文件夹中存在) - Move file to a folder or make a renamed copy if it exists in the destination folder os.rename 无法创建已存在的文件 - os.rename cannot create a file that already exists 使用带有 Python 的 glob 重命名多个文件(文件已存在) - rename multiple files using glob with Python (file already exists) 如果文件已存在于 python 中,我该如何重命名该文件 - How do i rename a file if it already exists in python Python 将文件复制到新目录并在文件名已存在时重命名 - Python copy files to a new directory and rename if file name already exists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM