Python中移动文件的方法

Python中移动文件的方法

技术背景

在Python编程中,经常会遇到需要移动文件的场景,例如文件的整理、备份等。这就需要借助Python的相关库和方法来实现类似mv命令的功能。

实现步骤

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

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

1
2
3
4
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(),但如果源文件和目标文件位于不同的磁盘上,它会先复制文件,然后删除源文件。

1
2
3
import shutil

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

使用pathlib.Path.rename()

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

1
2
3
from pathlib import Path

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

核心代码

批量移动文件

1
2
3
4
5
6
7
8
9
10
11
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)

封装为函数

1
2
3
4
5
6
7
8
9
10
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))

最佳实践

  • 当不确定源文件和目标文件是否在同一设备上时,建议使用shutil.move()
  • 使用os.path.join()来拼接文件路径,以避免跨平台问题。
  • 如果需要处理文件的元数据,要注意shutil.copy2()可能无法复制所有元数据。

常见问题

  • os.rename()无法处理跨设备文件移动:如果源文件和目标文件位于不同的磁盘上,os.rename()会抛出异常,此时应使用shutil.move()
  • 目标文件已存在:在Windows系统中,os.rename()会抛出异常,而os.replace()会直接替换该文件。使用shutil.move()时,在某些Python版本中也可能会出现问题,需要手动处理。
  • 使用~路径~是shell的构造,Python中应使用os.getenv('HOME')os.path.expanduser()来处理。

Python中移动文件的方法
https://119291.xyz/posts/2025-04-22.python-file-moving-methods/
作者
ww
发布于
2025年4月22日
许可协议