【问题标题】:Move the files from different paths and replace if any file already exists从不同的路径移动文件并替换如果任何文件已经存在
【发布时间】:2020-04-30 10:52:23
【问题描述】:

我有如下文件列表:

['/home/Test//A/Aa/hello1.c', '/home/Test/C/Aa/hello1.c', '/home/Test/B/Aa/hello1.c']

我正在尝试将所有这些文件从该路径移动到另一个路径。当我找到相同的文件名时,我需要替换现有的文件,因为我想以某种方式从现有路径中删除这些文件,所以如果存在相同的文件名,因为它们是相同的文件,我需要替换。

尝试如下:

import shutil
list_l1 = ['/home/Test//A/Aa/hello1.c', '/home/Test/C/Aa/hello1.c', '/home/Test/B/Aa/hello1.c']
for source in list_l1:
    shutil.move(source, '/home/AShekar/sample_try/sample/')

我收到错误消息 文件“/usr/lib/python2.7/shutil.py”,第 292 行,在移动中 引发错误,“目标路径 '%s' 已存在”% real_dst

提前致谢!!

【问题讨论】:

标签: python replace move shutil


【解决方案1】:

下面的 sn-p 将适用于 Python 3.8

    from shutil import copytree, rmtree
    import os
    src = os.path.join(os.getcwd(), 'src')
    dst = os.path.join(os.getcwd(), 'dst')
    copytree(src, dst, dirs_exist_ok=True)
    rmtree(src, ignore_errors=True)

【讨论】:

  • 不,我的方案不适用于 copytree 方法
  • 请。分享您的目录结构和您的期望。
猜你喜欢
  • 1970-01-01
  • 2019-05-04
  • 2016-05-01
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-01
相关资源
最近更新 更多