python之判断文件&文件夹是否存在,存在则删除,不存在则创建

1、删除文件与文件夹

import os
if os.path.exists(r'c:\test.xlsx'):
	os.remove(r'c:\test.xlsx')

使用os.remove删除文件夹会出现拒绝访问的错误,所以要使用以下方式进行删除

import os
import shutil
if os.path.exists(r'c:\1'):
	shutil.rmtree(r'c:\1')

2、创建文件与文件夹

创建文件

import os

current_path = os.getcwd()  #获取当前路径
print(current_path)
path = current_path+'\\test.txt' #在当前路径创建名为test的文本文件

if os.path.exists(path):
	print('exist')
else:
	os.mkdir(path)

创建文件夹

import os
current_path = os.getcwd()  #获取当前路径
path = current_path+'\\test' #在当前路径创建名为test的文件夹

if os.path.exists(path):
	print('exist')
else:
	os.mkdir(path)  #创建
发布了31 篇原创文章 · 获赞 2 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_27149279/article/details/105386462