首页 > 解决方案 > 是否有更简单的功能或一个衬垫来检查文件夹是否存在,如果不创建它并将特定文件粘贴到其中?

问题描述

我的目标是创建一个执行以下操作的函数:

我花了大约。15-20分钟通过这些:

https://www.programiz.com/python-programming/目录

加入列表中除最后一个 x 之外的所有内容

https://docs.python.org/3/library/pathlib.html#operators

这就是我要做的:

import os
from pathlib import Path, PurePath
from shutil import copy

#This path will change every time - just trying to get function right first 
path = 'C:/Users/Lampard/Desktop/Folder1/File.py'

#Used to allow suffix function
p = PurePath(path)

#Check if directory is a file not a folder
if not p.suffix:
    print("Not an extension")

#If it is a file
else:
    #Create new folder before last file
    #Change working directory
    split = path.split('/')
    new_directory = '/'.join(split[:-1])
    apply_new_directory = os.chdir(new_directory)
    #If folder does not exist create it
    try:
        os.mkdir('Archive')#Create new folder
    #If not, continue process to copy file and paste it into Archive
    except FileExistsError:
        copy(path, new_directory + '/Archive/' + split[-1])

这段代码好吗?- 有人知道更简单的方法吗?

标签: python

解决方案


在路径中找到文件夹/文件

print [name for name in os.listdir(".") if os.path.isdir(name)]

创建路径

    import os

# define the name of the directory to be created
path = "/tmp/year"

try:
    os.mkdir(path)
except OSError:
    print ("Creation of the directory %s failed" % path)
else:
    print ("Successfully created the directory %s " % path)

要移动和剪切文件,您可以使用


推荐阅读