You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中安全移动文件至其他目录,仅允许移动文件

确保仅移动文件的解决方案

要实现仅允许移动文件、当源为目录时执行失败的需求,只需在调用shutil.move前添加源路径类型校验即可,以下是跨平台(支持Windows和Unix)的实现方案:

方法一:使用os.path模块(兼容Python 2/3)

通过os.path.isfile()判断源路径是否为文件,若不是则主动抛出异常终止操作:

import os
import shutil

source = "/path/to/source_file"  # Windows下可写为 "c:\\mydir\\myfile.txt"
dest_dir = "/path/to/dest_dir"    # Windows下可写为 "c:\\newdir"

# 校验源路径是否为文件,不存在或为目录时抛出异常
if not os.path.isfile(source):
    raise ValueError("仅支持移动文件,当前源路径是目录或不存在")

shutil.move(source, dest_dir)

方法二:使用pathlib模块(Python 3.4+,更简洁)

利用现代路径处理库pathlib的is_file()方法做校验,代码可读性更强:

from pathlib import Path
import shutil

source = Path("/path/to/source_file")  # Windows下可写为 Path("c:\\mydir\\myfile.txt")
dest_dir = Path("/path/to/dest_dir")    # Windows下可写为 Path("c:\\newdir")

# 校验源路径是否为文件
if not source.is_file():
    raise ValueError("仅支持移动文件,当前源路径是目录或不存在")

# Python 3.6+ 可直接将Path对象传入shutil.move,无需转字符串
shutil.move(source, dest_dir)

说明

  • 两种方案均跨平台,os.path.isfile和pathlib.Path.is_file会自动适配Windows与Unix的文件系统规则,正确区分文件与目录。
  • 若希望静默终止而非抛出异常,可将raise语句替换为return或其他自定义逻辑。

内容的提问来源于stack exchange,提问作者paulj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 17:55:58