python (os.path, glob) 路径读取,文件读取


提示:python读取文件挺方便的,这篇就介绍一下如何使用os.path搞定路径的问题


读取(strip, split)

# import
import os
import os.path as osp
import glob

# 更加深入
data_root = 'a/b/c'
data_path = osp.join(a, 'd', 'e') # a/b/c/d/e

# 读取文件夹下所有文件 并生成list
# 例如 data_path 下面时一堆 png图片
images_list = glob.glob(osp.join(data_path, '*.png'))
# images_list 是一个list, 存放着所有png照片的名称


# 一个读取的例子,注意 *strip**split*
shapes = []
with open(anno_dir, 'r') as anno_f:
    lines = anno_f.readlines()
    for line in lines:
        coords = []
        coords_str = line.strip().split(' ')
        for i in range(len(coords_str) // 2):
            coord_x = float(coords_str[2 * i]) + offset_x
            coord_y = float(coords_str[2 * i + 1]) + offset_y
            coords.append(coord_x)
            coords.append(coord_y)
        if len(coords) > 3:
            shapes.append(coords)

os.path.dirname()

语法:os.path.dirname(path)
功能:去掉文件名,返回目录

print(os.path.dirname(“E:/Read_File/read_yaml.py”))
#结果:
E:/Read_File

os.path.basename(path)

返回path最后的文件名。如果path以/或\结尾,那么就会返回空值

print(os.path.basename(“E:/Read_File/read_yaml.py”))
#结果:
read_yaml.py

创建不存在的文件夹

if not osp.exists(mask_dir):
   os.makedirs(mask_dir)
   # os.mkdir(mask_dir)
# 区别在于,os.makedirs会递归的建立输入的路径,即使是上层的路径不存在,它也会建立这个路径,
# 而os.mkdir父级路径不存在,那么就会报错。

创建txt

当txt的文件夹已经存在时,可以直接用open(path, ‘w’)直接写就行,可以直接创建

## 二维list (lanes), 每一个内部list 写一行。
with open(save_path, 'w') as write_f:
     for idx, coord_line in enumerate(lines):
         for coord in coord_line:
             print(coord, file=write_f, end=' ')
         if idx != len(lines) - 1:
             print(file=write_f) # print a new line, end= 默认是换行符
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值