您的位置:首页 > 编程语言 > Python开发

Python新建/删除文件夹

2016-05-13 09:52 477 查看
新建以当前日期为名的文件夹

import datetime,os,shutil
today = datetime.datetime.now().date().strftime('%Y%m%d')
pathh= os.path.join('e:\\a','bb',today ) #可以连接多级目录
print pathh #返回 e:\a\bb\20160513
if not os.path.exists(pathh):
os.makedirs(pathh) #可以创建多级不存在的目录 os.makedir(pathh)只能创建单级目录

os.rmdir(pathh) #只能删除20160513目录,e:\a\bb还存在
shutil.rmtree('e:\\a') #空目录、有内容的目录都可以删除


复制文件:
shutil.copyfile("oldfile","newfile") oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile") oldfile只能是文件夹,newfile可以是文件,也可以是目标目录

复制文件夹:
shutil.copytree("olddir","newdir") olddir和newdir都只能是目录,且newdir必须不存在

重命名文件(目录)
os.rename("oldname","newname") 文件或目录都是使用这条命令,oldname和newname都要是filepath

移动文件(目录)
shutil.move("oldpos","newpos")

删除文件
os.remove("file")

转换目录
os.chdir("path") 换路径

判断是否存在
os.path.isdir("aa") 判断目标是否目录
os.path.isfile("bb.txt") 判断目标是否文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: