2021-09-13

本文详细介绍了Python中os模块的常用函数,如获取当前路径、绝对路径、列出目录、连接路径与文件名、判断路径类型等。同时,也讲解了shutil模块的copy和rmtree函数,用于文件复制和递归删除文件夹。通过实例展示了如何在实际编程中应用这些功能。
摘要由CSDN通过智能技术生成

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)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值