python文件操作—os包
记录自己的使用经历!!!
1.os.getcwd()
获取当前路径
2.os.path.abspath(path)
获取绝对路径
3.os.listdir(path)
打开路径文件夹
4.os.path.join(path,name)
连接路径与文件名,文件名可有多个
os.path.join(os.getcwd(),"dataset","1.jpg")
5.os.path.isdir(path)
判断是否是文件夹
root = os.path.join(os.getcwd(), "flower_data", "flower_photos")
flower_class = [cal for cal in os.listdir(root) if os.path.isdir(os.path.join(root, cal))
6.os.path.splitext()
分离文件路径与文件名,返回一个元组
images = [os.path.join(root, cla, i) for i in os.listdir(cla_path)
if os.path.splitext(i)[-1] in support]
7.os.path.exists()
判断路径是否存在
img_path = "D:\\picture\\one"
if not os.path.exists(img_path):
os.mkdir(img_path)
8.os.path.isdir(path)
判断是否是文件夹
9.shutil.copy(src,dst)
将src内容复制到dst
img_path = os.path.join(cla_path, img)
new_path = os.path.join(val_path, cla)
copy(img_path, new_path)
10.shutil.rmtree(path)
递归删除整个文件夹下所有文件,包括此文件夹;
def mk_dir(path: str):
if os.path.exists(path):
rmtree(path)
os.mkdir(path)