分享:浅谈python shutil 的move与copy方法,他们对文件名的大小写不敏感,但是很有趣(windows系统下)。

python的内置模块shutil 可以提供给我们一些操作文件以及目录的方法。

import shutil

#复制文件:
shutil.copyfile(src, dst) #src和dst都只能是文件
shutil.copy(src, dst) #src只能是文件夹,dst可以是文件,也可以是目标目录

#移动文件/目录或重命名
shutil.move(src, dst) 如果src与dst在同一级目录,那么会执行重命名操作,等同于os.rename("oldname","newname")

值得注意的是shutil 对 src 的大小写并不敏感,只要名字内容一样就可以实现操作。但是执行的结果却是目dst 的名字与src的名字一样。

例如:

import shutil
import os

path = os.path.split(os.path.realpath("demo.py"))[0]
src= path + '/MoVE_results.xlsx'
dst  = path + '/New Folder'
shutil.move(src,dst)

我本地有一个move_results.xlsx 的文件,但是src 写成MoVE_results.xlsx也可以匹配到,但是移动到New Folder这个目录下后,

文件名字变为  MoVE_results.xlsx。这就相当于移动并且重命名操作!

 

通过查看源码可以发现:

def move(src, dst):
    """Recursively move a file or directory to another location. This is
    similar to the Unix "mv" command.

    If the destination is a directory or a symlink to a directory, the source
    is moved inside the directory. The destination path must not already
    exist.

    If the destination already exists but is not a directory, it may be
    overwritten depending on os.rename() semantics.

    If the destination is on our current filesystem, then rename() is used.
    Otherwise, src is copied to the destination and then removed.
    A lot more could be done here...  A look at a mv.c shows a lot of
    the issues this implementation glosses over.

    """
    real_dst = dst
    if os.path.isdir(dst):
        if _samefile(src, dst):  
            # We might be on a case insensitive filesystem,
            # perform the rename anyway.
            os.rename(src, dst)
            return

        real_dst = os.path.join(dst, _basename(src))
        if os.path.exists(real_dst):
            raise Error, "Destination path '%s' already exists" % real_dst
    try:
        os.rename(src, real_dst)  #这个是关键
    except OSError:
        if os.path.isdir(src):
            if _destinsrc(src, dst):
                raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
            copytree(src, real_dst, symlinks=True)
            rmtree(src)
        else:
            copy2(src, real_dst)
            os.unlink(src)

重点来了:

对于windows 系统,在匹配时会忽略大小写。而在linux系统,是严格按照大小写匹配的。

所以os.rename()在windows系统下可以忽略大小写进行重命名操作,而linux系统却不能。相应的shutil.move()也是这样。

故,我用window系统进行剪切操作时,大小写不统一也可以匹配,移动后名字变为 rea_dst。

发现shutil模块在python3进行了更新,对于shutil.copy(src,dst)方法。在python3中可以返回成功后dst的路径,而python2只会返回None.

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值