【问题标题】:how to copy files and directory from source to destination using python如何使用python将文件和目录从源复制到目标
【发布时间】:2020-01-31 18:54:20
【问题描述】:

我想要一个 python 脚本来完成这三个任务:

  1. 检查路径是否包含复制到特定目标的word文件
  2. 检查路径是否包含复制到特定目标的pdf文件
  3. 检查路径是否包含目录并将洞文件夹复制到 具体目的地。

出于这个原因,我使用 os.walk() 列出路径的目录和文件 我正在使用 shutil library 来复制文件和目录。

代码

import os
from distutils.dir_util import copy_tree
import shutil
from os import path
import datetime

def main():
    src = "C:/Users/LT GM/Desktop/Python_files/"


    dst2 = "C:/Users/LT GM/Desktop/"
    for root,dirs,files in os.walk(src):
        for name in files:
            print("files: ",os.path.join(root,name))
        for name in dirs:
            copieddst = copy_tree(src,dst2)
            print("directory: ",os.path.join(root,name))
            print(" coppied directory :{0}".format(copieddst) )
    # make a duplicate of an existing file
        if path.exists(src):
    # get the path to the file in the current directory
            print("****")
            src = path.realpath("pandas.pdf")

    #seperate the path from the filter
        head, tail = path.split(src)
        print("path:" +head)
        print("file:" +tail)    
        dst =str(datetime.date.today()) + tail  
    # nowuse the shell to make a copy of the file
        shutil.copy(src, dst)

if __name__=="__main__":
    main()

问题是我可以复制文件或目录的内容。不是hole目录以及如何检查它的pdfdoc文件?

【问题讨论】:

    标签: python shutil os.walk


    【解决方案1】:

    如果你想复制目录而不是文件,那么使用shutil.copytree。在用法上与shutil.copy2类似,即:

    import shutil
    shutil.copytree('mydir', 'mydircopy')
    

    请注意,默认情况下dirs_exist_okFalse,这意味着在启动shutil.copytree 时目标不应该存在。

    【讨论】:

    • 如果你这样做shutil.copytree('mydir', 'mydircopy', dir_exists_ok=True),你可以复制到已经存在的目的地,但是请记住:3.8 版中的新功能:dirs_exist_ok 参数。 这意味着你只能使用它Python 3.8 或更新版本
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    相关资源
    最近更新 更多