python shutil.move移动文件或目录方式

 更新时间:2024年12月30日 09:49:51   作者:jn10010537  
`shutil.move()`函数可以移动文件或目录,移动目录时,如果目标目录不存在,会创建该目录并将源目录内容移动到新目录;如果目标目录存在,则将源目录移动到目标目录下,移动文件时,如果目标路径是目录,则将文件移动到该目录下并重命名

背景

shutil.move可以实现文件或者目录的移动。

打印:

import shutil
help(shutil.move)
# 打印如下:
'''
move(src, dst, copy_function=<function copy2 at 0x000001D1CE15F8C8>)
    Recursively move a file or directory to another location. This is
    similar to the Unix "mv" command. Return the file or directory's
    destination.
    
    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. Symlinks are
    recreated under the new name if os.rename() fails because of cross
    filesystem renames.
    
    The optional `copy_function` argument is a callable that will be used
    to copy the source or it will be delegated to `copytree`.
    By default, copy2() is used, but any function that supports the same
    signature (like copy()) can be used.
    
    A lot more could be done here...  A look at a mv.c shows a lot of
    the issues this implementation glosses over.
'''

查看shutil.move函数:

def move(src, dst, copy_function=copy2):
    """Recursively move a file or directory to another location. This is
    similar to the Unix "mv" command. Return the file or directory's
    destination.

    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. Symlinks are
    recreated under the new name if os.rename() fails because of cross
    filesystem renames.

    The optional `copy_function` argument is a callable that will be used
    to copy the source or it will be delegated to `copytree`.
    By default, copy2() is used, but any function that supports the same
    signature (like copy()) can be used.

    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.islink(src):
            linkto = os.readlink(src)
            os.symlink(linkto, real_dst)
            os.unlink(src)
        elif os.path.isdir(src):
            if _destinsrc(src, dst):
                raise Error("Cannot move a directory '%s' into itself"
                            " '%s'." % (src, dst))
            copytree(src, real_dst, copy_function=copy_function,
                     symlinks=True)
            rmtree(src)
        else:
            copy_function(src, real_dst)
            os.unlink(src)
    return real_dst

移动目录

shutil.move(old,new)用来移动:文件夹:

old是一个目录
new是一个存在的目录,这时会把old目录移动到new下面;可以new也可以是一个不存在的目录,这时会创建这个不存在的目录,然后把old目录下面的所有文件移动到创建的目录里面。

举例:

import shutil
# 移动目录
shutil.move("./folder_123","./folder_456")

./folder_123:
-------------------目录一定要存在,否则报错;

./folder_456:
-------------------目录不存在时,创建该目录,并将./folder_123目录下的文件移动到./folder_456目录下;
-------------------目录存在时,将folder_123文件夹移动到folder_456文件夹内;

移动文件

shutil.move(old,new)用来移动:文件:

old是一个文件路径
newnew是一个存在的文件夹路径或是一个存在的文件夹路径加文件名

注意:

  • new如果是一个不存在的文件夹路径,则会将原文件移动到new文件夹上一目录中,且以该文件夹的名字重命名。
  • new如果是一个不存在的文件夹路径加文件名,则会报错。

举例:

import shutil
# 移动文件
shutil.move("./mask/sample.jpg","./folder_456/folder_789")

./mask/sample.jpg:
-------------------路径一定要存在,否则报错;

./folder_456/folder_789:
-------------------目录存在时,将./mask/sample.jpg文件移动到./folder_456/folder_789目录下;
-------------------目录不存在时,具体:folder_456存在,folder_789不存在时,将./mask/sample.jpg移动到folder_456文件夹下,并将sample.jpg文件改名为folder_789;
-------------------目录不存在时,具体:folder_456不存在,folder_789不存在时,报错!

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 如何利用Python动态展示排序算法

    如何利用Python动态展示排序算法

    Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,能够简单、有效地实现面向对象编程,下面这篇文章主要给大家介绍了关于如何利用Python动态展示排序算法的相关资料,需要的朋友可以参考下
    2021-10-10
  • 使用Numpy读取CSV文件,并进行行列删除的操作方法

    使用Numpy读取CSV文件,并进行行列删除的操作方法

    今天小编就为大家分享一篇使用Numpy读取CSV文件,并进行行列删除的操作方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07
  • Python中如何调用系统命令和进程

    Python中如何调用系统命令和进程

    在Python编程中,subprocess库是一个功能强大的工具,本文将详细介绍subprocess库的功能和应用场景,并通过代码示例进行说明,需要的可以了解下
    2025-02-02
  • Python2和Python3中print的用法示例总结

    Python2和Python3中print的用法示例总结

    在Python 3中接触的第一个很大的差异就是缩进是作为语法的一部分,这和C++等其他语言确实很不一样,所以要小心,其中python3和python2中print的用法有很多不同,这篇文章主要给大家介绍了关于Python2和Python3中print用法的相关资料,需要的朋友可以参考下。
    2017-10-10
  • Python的多态性实例分析

    Python的多态性实例分析

    这篇文章主要介绍了Python的多态性,以实例形式深入浅出的分析了Python在面向对象编程中多态性的原理与实现方法,需要的朋友可以参考下
    2015-07-07
  • Pandas之数据追加df.append方式

    Pandas之数据追加df.append方式

    这篇文章主要介绍了Pandas之数据追加df.append方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • Python使用Spire.XLS for Python实现TXT转Excel

    Python使用Spire.XLS for Python实现TXT转Excel

    在数据处理工作中,我们可能会遇到将TXT文本文件转换为Excel格式的需求,本文将介绍如何使用 Spire.XLS for Python 库,编写一个能够自动检测分隔符并完成转换的智能工具,希望对大家有所帮助
    2026-05-05
  • python应用文件读取与登录注册功能

    python应用文件读取与登录注册功能

    这篇文章主要介绍了python应用文件读取写登录注册功能,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-09-09
  • selenium+python设置爬虫代理IP的方法

    selenium+python设置爬虫代理IP的方法

    这篇文章主要介绍了selenium+python设置爬虫代理IP的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-11-11
  • 详解用python自制微信机器人,定时发送天气预报

    详解用python自制微信机器人,定时发送天气预报

    这篇文章主要介绍了用python自制微信机器人,定时发送天气预报,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03

最新评论