Python:复制、移动文件到指定文件夹

需要考虑的问题:

  • 指定文件夹是否存在,不存在则创建
  • 在指定文件夹中是否存在同名文件,是覆盖还是另存为
import os
import shutil
import traceback


def copyfile(srcfile, dstpath, replace=False):
    """复制文件到指定文件夹
    @param srcfile: 原文件绝对路径
    @param dstpath: 目标文件夹
    @param replace: 如果目标文件夹已存在同名文件,是否覆盖
    """
    try:
        if not os.path.isfile(srcfile):
            print("%s not exist!" % (srcfile))
        else:
            fpath, fname = os.path.split(srcfile)  # 分离文件名和路径
            suffix = os.path.splitext(srcfile)[-1]
            # print(fpath, fname, suffix)
            if not os.path.exists(dstpath):
                os.makedirs(dstpath)  # 创建路径
            if replace:
                dstfile = os.path.join(dstpath, fname)
                shutil.copy(srcfile, dstfile)  # 复制文件
                print("copy %s -> %s" % (srcfile, dstfile))
            else:
                i = 1
                while True:
                    add = ' (%s)' % str(i) if i != 1 else ''
                    dstfile = os.path.join(dstpath, fname.replace(suffix, add + suffix))
                    if os.path.exists(dstfile) and i <= 10:
                        i += 1
                    else:
                        shutil.copy(srcfile, dstfile)  # 复制文件
                        print("copy %s -> %s" % (srcfile, dstfile))
                        break
            return dstfile
  
    except Exception as e:
        print('文件复制失败', srcfile)
        traceback.print_exc()
        
import os
import shutil
import traceback

def movefile(srcfile, dstpath, replace=False):
    """移动文件到指定文件夹
    @param srcfile: 原文件绝对路径
    @param dstpath: 目标文件夹
    @param replace: 如果目标文件夹已存在同名文件,是否覆盖
    """
    try:
        if not os.path.isfile(srcfile):
            print("%s not exist!" % (srcfile))
        else:
            fpath, fname = os.path.split(srcfile)  # 分离文件名和路径
            suffix = os.path.splitext(srcfile)[-1]
            # print(fpath, fname, suffix)
            if not os.path.exists(dstpath):
                os.makedirs(dstpath)  # 创建路径
            if replace:
                dstfile = os.path.join(dstpath, fname)
                shutil.move(srcfile, dstfile)  # 复制文件
                print("move %s -> %s" % (srcfile, dstfile))
            else:
                i = 1
                while True:
                    add = ' (%s)' % str(i) if i != 1 else ''
                    dstfile = os.path.join(dstpath, fname.replace(suffix, add + suffix))
                    if os.path.exists(dstfile) and i <= 10:
                        i += 1
                    else:
                        shutil.move(srcfile, dstfile)  # 复制文件
                        print("move %s -> %s" % (srcfile, dstfile))
                        break
    except Exception as e:
        print('文件移动失败', srcfile)
        traceback.print_exc()

复制文件到指定文件夹V2:

  1. 判断源文件是否存在
  2. 判断目标文件夹是否存在
  3. 判断是否已存在该文件
  4. 判断已存在文件是否打开
  5. 判断是否需要替换掉已存在文件

注意:复制文件会改变时间属性(创建日期、修改日期),不再是源文件的时间属性

import os
import shutil
import traceback


def copyfile(srcfile, dstpath, replace=False):
    """复制文件到指定文件夹
    @param srcfile: 原文件绝对路径
    @param dstpath: 目标文件夹
    @param replace: 如果目标文件夹已存在同名文件,是否覆盖
    """
    try:
        # 判断源文件是否存在
        assert os.path.isfile(srcfile), "源文件不存在"
        basename = os.path.basename(srcfile)
        fname = os.path.splitext(basename)[0]  # 不带后缀的文件名
        suffix = os.path.splitext(srcfile)[-1]
        # 判断目标文件夹是否存在
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)  # 创建文件夹,可递归创建文件夹,可能创建失败
        # 判断目标文件夹是否存在
        assert os.path.exists(dstpath), "目标文件夹不存在"

        # 开始尝试复制文件到目标文件夹
        i = 0
        while True:
            i += 1
            add = '(%s)' % str(i) if i != 1 else ''
            dstfile = os.path.join(dstpath, fname + add + suffix)
            opened_dstfile = os.path.join(dstpath, '~$' + fname + add + suffix)  # 已打开文件
            # 判断目标文件夹是否存在该文件
            if not os.path.exists(dstfile):
                shutil.copy(srcfile, dstfile)  # 不存在则复制文件
                break

            # 存在该文件,则判断已存在文件是否打开
            if os.path.exists(opened_dstfile):
                # 已打开则创建下一个新文件
                continue

            # 已存在文件没有打开的情况
            if replace:
                shutil.copy(srcfile, dstfile)  # 复制文件
                break
            # 不覆盖已存在文件,则创建下一个新文件

        return dstfile

    except AssertionError as e:
        print('文件复制失败', e, srcfile)
    except Exception as e:
        print('文件复制失败', e, srcfile)

if __name__ == "__main__":

    srcfile = r"C:\Users\Administrator\Desktop\源文件夹\test.txt"
    dir = r"C:\Users\Administrator\Desktop\目标文件夹"
    print(copyfile(srcfile, dir, replace=True))

Python复制文件到指定文件夹,遇到相同文件名的处理

https://www.cnblogs.com/johnthegreat/p/12748790.html

python复制、移动文件到指定文件夹_python移动文件到指定文件夹-CSDN博客

文件侠告诉你,Python复制文件的N种姿势! - 云+社区 - 腾讯云

  • 22
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用shutil库中的copyfile函数来实现将文件复制指定目录下的操作。首先,你需要导入shutil库和os库。然后,你可以使用os.listdir函数来获取指定目录下的所有文件列表。接下来,你可以使用一个循环来遍历文件列表,并使用shutil.copyfile函数将每个文件复制到目标目录下。下面是一个示例代码: ```python import os import shutil source_dir = "D:\\notes\\python\\资料\\" target_dir = "d:\\copy\\newname\\" for file_name in os.listdir(source_dir): if file_name.lower().endswith(".py"): source_file = os.path.join(source_dir, file_name) target_file = os.path.join(target_dir, file_name) shutil.copyfile(source_file, target_file) ``` 在这个示例中,我们首先定义了源目录和目标目录的路径。然后,使用os.listdir函数获取源目录下的所有文件列表。接下来,我们使用一个循环来遍历文件列表,并使用shutil.copyfile函数将每个以".py"结尾的文件复制到目标目录下。请注意,你需要根据你的实际情况修改源目录和目标目录的路径。 #### 引用[.reference_title] - *1* [Python--将文件夹及其中的全部文件拷贝到指定路径下](https://blog.csdn.net/qq_33782655/article/details/127394877)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [用python实现将文件拷贝到指定目录](https://blog.csdn.net/zd147896325/article/details/79870131)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值