【问题标题】:How to select a specific directory to copy from its source to new destination using Python?如何使用 Python 选择要从其源复制到新目标的特定目录?
【发布时间】:2020-05-27 15:28:21
【问题描述】:

我有一个脚本,可以将文件夹和文件从它们的源复制到新的目的地,该脚本使用shutil 模块可以正常工作。但我正在硬编码文件夹的源代码。

我需要让脚本选择具有特定名称的所需文件夹。 as
pdf 11-12-02-2020 所以它是 pdf + 昨天的日期 - 当前日期 - 当前月份 - 当前年份。

我该怎么做?

代码:

import os
import shutil
from os import path
import datetime

src = "I:\\"
src2 = "I:/pdf 11-12-02-2020"

dst = "C:/Users/LT GM/Desktop/pdf 11-12-02-2020/"


def main():
    copy()

def copy():
    if os.path.exists(dst): 
        shutil.rmtree(dst)
        print("the deleted folder is :{0}".format(dst))
        #copy the folder as it is (folder with the files)
        copieddst = shutil.copytree(src2,dst)
        print("copy of the folder is done :{0}".format(copieddst))
    else:
        #copy the folder as it is (folder with the files)
        copieddst = shutil.copytree(src2,dst)
        print("copy of the folder is done :{0}".format(copieddst))

if __name__=="__main__":
    main()

【问题讨论】:

  • 作为旁注,我通常会避免在文件夹/文件名中包含空格。一些库不能很好地处理空格(即 os 库)。如果需要,则使用 dst=r'string' 可能会更好。

标签: python rename shutil


【解决方案1】:

您正在寻找datetime 模块。

此外,您可能希望使用os 模块为您正确解析路径,请参阅this,因为src 变量似乎未使用,最好将其删除,记住所有这些:

import calendar
import os
import shutil
from datetime import date
from os import path

def yesterday():
    day = int(date.today().strftime("%d"))
    month = int(date.today().strftime("%m"))
    year = int(date.today().strftime("%Y"))
    if day != 1:
        return day - 1
    long_months = [1, 3, 5, 7, 8, 10, 12]
    if month in long_months:
        return 31
    elif month == 2:
        if calendar.isleap(year):
            return 29
        return 28
    else:
        return 30

name = "pdf " + str(yesterday()) + date.today().strftime("-%d-%m-%Y")

src2 = os.path.join("I:/", name)

dst = os.path.join(os.path.expanduser("~"), "Desktop",name)

附带说明,在这种情况下 dst = os.path.join(os.path.expanduser("~"), "Desktop" ,name) 有效,其实不建议用,看我的回答here

【讨论】:

  • 如果我有多个文件夹,例如 pdf 11-12-02-2020 & pdf 10-11-02-2020 & pdf 9-10-02-2020 如何复制所有这些文件夹?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-10
相关资源
最近更新 更多