Python判断文件或目录是否存在(exists)、判断是否为目录(文件夹)、删除、创建目录(文件夹)挺好用

今日,网上学习使用os.path.exists, 感觉非常好用。传说码农一定文案好,加目录更香。
目录:
一 内容:python下判断,建立和删除文件夹。
二 如何更好的记住命令?
三 单级目录的栗子
四 多级目录的栗子
五 参考链接,感谢大神作品

一 Python判断文件或目录是否存在(exists)、判断是否为目录(文件夹)、删除、创建目录(文件夹)

二 需要注意单个目录和多个目录的命令不同,
单个目录命令简单,简写,os.mkdir(test_path), os.rmdir(test_path),
多级目录字母复杂,全程,os.makedires(test_paths), os.removedirs(test_paths)`

三 单级目录的例子:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# judge if path exist
if os.path.exists(test_path):
	# judge if the path is dir
	if os.path.isdir(test_path):
		print(test_path, 'is dir')
	# judge whether the path is a file.
	elif os.path.isfile(test_path):
		print(test_path, 'is file')
else:
	# make a folder first level.
	os.mkdir(test_path)

四 多级目录的例子。

#by steven0410
if os.path.exists(test_paths):
	# judge if the path is dir
	if os.path.isdir(test_paths):
		print(test_paths, 'is dir')
		os.removedirs(test_paths)
		print(test_paths, '_dirs are removed')
	# judge whether the path is a file.
	elif os.path.isfile(test_paths):
		print(test_paths, 'is file')
		# If it is file, we can also delete it.
		os.remove(test_paths)
		print(test_paths, "_file is removed.")
else:
	os.makedirs(test_paths)
	print(test_paths, "are made!")
	os.removedirs(test_paths)
	print(test_paths, "are removed!")

五 参考链接:感谢大神的作品。
https://blog.csdn.net/qq_39839807/article/details/104193237

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值