python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python移动文件方法

Python中移动文件的实现方法汇总

作者:1010n111

在Python编程中,经常会遇到需要移动文件的场景,例如文件的整理、备份等,这就需要借助Python的相关库和方法来实现类似mv命令的功能,本文给大家汇总了Python移动文件的实现方法,需要的朋友可以参考下

Python中移动文件的方法

实现步骤

使用os.rename()或os.replace()

这两个函数都可以用于重命名或移动文件。使用时,需要确保目标目录已经存在。在Windows系统中,如果目标文件已存在,os.rename()会抛出异常,而os.replace()会直接替换该文件。

import os

os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

使用shutil.move()

shutil.move()是最接近Unixmv命令的方法。它在大多数情况下会调用os.rename(),但如果源文件和目标文件位于不同的磁盘上,它会先复制文件,然后删除源文件。

import shutil

shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

使用pathlib.Path.rename()

在Python 3.4及以后的版本中,可以使用pathlib库的Path类来移动文件。

from pathlib import Path

Path("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")

核心代码

批量移动文件

import os
import shutil

path = "/volume1/Users/Transfer/"
moveto = "/volume1/Users/Drive_Transfer/"
files = os.listdir(path)
files.sort()
for f in files:
    src = path + f
    dst = moveto + f
    shutil.move(src, dst)

封装为函数

import os
import shutil
import pathlib
import fnmatch

def move_dir(src: str, dst: str, pattern: str = '*'):
    if not os.path.isdir(dst):
        pathlib.Path(dst).mkdir(parents=True, exist_ok=True)
    for f in fnmatch.filter(os.listdir(src), pattern):
        shutil.move(os.path.join(src, f), os.path.join(dst, f))

最佳实践

常见问题

到此这篇关于Python中移动文件的实现方法汇总的文章就介绍到这了,更多相关Python移动文件方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文