python - 是否有更简单的功能或一个衬垫来检查文件夹是否存在,如果不创建它并将特定文件粘贴到其中?
问题描述
我的目标是创建一个执行以下操作的函数:
- 用文件声明路径,而不仅仅是文件夹。例如
'C:/Users/Lampard/Desktop/Folder1/File.py'
- 在与声明的文件路径相同的文件夹中创建一个文件夹 - 将其称为“存档”
- 剪切文件并将其粘贴到刚刚创建的新文件夹中。
- 如果文件夹“存档”已经存在 - 然后只需将文件剪切并粘贴到那里
我花了大约。15-20分钟通过这些:
https://www.programiz.com/python-programming/目录
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])
这段代码好吗?- 有人知道更简单的方法吗?
解决方案
在路径中找到文件夹/文件
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)
要移动和剪切文件,您可以使用此库
推荐阅读
- java - 添加软链接属性spring-data-rest?
- nginx - 如何在 nginx 服务器中只监听 443
- reporting-services - SSRS - 分隔字符串的一部分并返回
- php - array_key_exists 和 ?? 在 php 7.x 中
- javascript - 如果它们有索引,如何登录控制台javascript数组项目属性
- azure - 一对一处理服务总线队列消息
- kubernetes - Helm chart 在 configmap 更改时重新启动 pod
- c - C、MPI:程序未终止且未打印数字
- mysql - Laravel 更新获取更新的 id
- entity-framework-core - SQLite 与 SQLServer 之间的实体框架核心数据类型转换差异