如何使用Python选择要从其源复制到新目标的特定目录?

2024-10-01 04:49:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我需要的是让脚本选择它具有特定名称的所需文件夹。作为
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()

Tags: theimport脚本文件夹pdfisosmain
1条回答
网友
1楼 · 发布于 2024-10-01 04:49:18

您正在寻找^{}模块

此外,您可能希望使用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

相关问题 更多 >