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))
最佳实践
- 当不确定源文件和目标文件是否在同一设备上时,建议使用
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中移动文件的实现方法汇总的文章就介绍到这了,更多相关python移动文件方法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论