尝试将python移动到

2024-06-09 05:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

Nvm,没用。谢谢你的努力。你知道吗


Tags: nvm
2条回答

有一个内置的库可以检查文件是否是图像。此外,还需要遍历目录(文件夹)中的文件。类似的方法应该有效(未经测试):

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

为什么不在搬家前检查一下呢。像下面这样

注意:当文件存在时,可以进行不同类型的重命名。我只是在扩展上加了一个新的。不完全是你想要的,但这应该给你一个想法

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:

相关问题 更多 >