Python实用记录(四):os模块-去后缀或者改后缀/指定目录下图片或者子目录图片写入txt/csv

简介: 本文介绍了如何使用Python的os模块来操作文件,包括更改文件后缀、分割文件路径和后缀、将指定目录下的所有图片写入txt文档,以及将指定目录下所有子目录中的图片写入csv文档,并为每个子目录分配一个标签。

1.改后缀

这个代码是指定路径,但是里面的具体文件名不知道,能够罗列所有的指定文件名和修改后缀,如果要获取具体路径下的文件文件名和后缀看下面这个目录

import os
def read_evr_yuc(file_path):
    dirpaths=os.listdir(file_path)
    yuv_name=[]
    name=[]
    new_name=[]
    for i in dirpaths:
        yuv_name.append(i)
        portion=os.path.splitext(i) #把文件名拆分为名字和后缀
        if portion[1] == ".yuv": #指定里面所有yuv的后缀的文件
            newname = portion[0] + ".code"
            new_name.append(newname)
            name.append(portion[0])
    print(yuv_name)
    print(name)
    print(new_name)    

if __name__ == '__main__':
    file_path='D:/pycharm/match/huffman/yuc_file/'
    read_evr_yuc(file_path)

2.划分路径和文件名、后缀名

#########start 获取文件路径、文件名、后缀名############
def get_splitfile(filename):
    (filepath,tempfilename) = os.path.split(filename)
    (shotname,extension) = os.path.splitext(tempfilename)
    print(filepath)
    print(shotname)
    print(extension)
    return filepath,shotname,extension
#########end 获取文件路径、文件名、后缀名############

path='F:/Dataset/cool/1.jpg'
get_splitfile(path)

3.指定目录下所有的图片写入到txt文档

"""把指定目录下所有的图片写入到txt文档中"""
import os
img_path='F:/pycharm/Pytorch2TensorRT-master/face/'
txtfile='F:/pycharm/Pytorch2TensorRT-master/my_files/face.txt'
os.makedirs(os.path.dirname(txtfile),exist_ok=True)
dirpaths=os.listdir(img_path)
f=open(txtfile,'w')
for dirpath in dirpaths:
    # print(dirpath)
    path=os.path.join(img_path,dirpath)
    print(path)
    f.write(path+'\n')

4.指定目录下所有的子目录(写上对应的label)对应的所有图片写入到csv文档

import os,glob,cv2,random,csv
def work():
    name2label = {}
    path='pokemon/'
    for name in sorted(os.listdir(os.path.join(path))):
        # 得到全部子目录
        if not os.path.isdir(os.path.join(path, name)):
            # 用于判断对象是否为一个目录
            continue
        name2label[name] = len(name2label.keys())
    print(name2label)
    images = []
    for name in name2label.keys():
        images += glob.glob(os.path.join(path, name, '*.png'))
        images += glob.glob(os.path.join(path, name, '*.jpg'))
        images += glob.glob(os.path.join(path, name, '*.jpeg'))
    # print(len(images), images)
    random.shuffle(images)
    with open(os.path.join(path, 'face.csv'), mode='w', newline='') as f:
        writer = csv.writer(f)
        for img in images:  # 'pokemon\\bulbasaur\\00000000.png' os.sep不用距离根据\\和/进行划分
            print(img)
            img=img.replace('\\','/') # 将里面的\换/
            # name = img.split(os.sep)[-2]
            (filepath, tempfilename) = os.path.split(img) # 获取路径、图片文件名
            (filepath1, tempfilename1) = os.path.split(filepath) # 获取剩余路径下的文件路径、文件名
            (filename, extension) = os.path.splitext(tempfilename1) # 获取文件路径、文件名
            print(filename)
            label = name2label[filename]
            # pokemon/squirtle/00000183.jpg 4
            writer.writerow([img, label])
        print('writen into csv file:', filename)

    # read from csv file
    images, labels = [], []
    with open(os.path.join(path, 'face.csv')) as f:
        reader = csv.reader(f)
        for row in reader:
            # pokemon/squirtle\00000183.jpg 4
            img, label = row
            label = int(label)
            images.append(img)
            labels.append(label)
    assert len(images) == len(labels)
    return  images,labels
images,labels=work()
print(images,labels)
目录
相关文章
|
28天前
|
测试技术 Python
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
106 31
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
|
2月前
|
Python
Python Internet 模块
Python Internet 模块。
133 74
|
3月前
|
算法 数据安全/隐私保护 开发者
马特赛特旋转算法:Python的随机模块背后的力量
马特赛特旋转算法是Python `random`模块的核心,由松本真和西村拓士于1997年提出。它基于线性反馈移位寄存器,具有超长周期和高维均匀性,适用于模拟、密码学等领域。Python中通过设置种子值初始化状态数组,经状态更新和输出提取生成随机数,代码简单高效。
141 63
|
3月前
|
测试技术 Python
手动解决Python模块和包依赖冲突的具体步骤是什么?
需要注意的是,手动解决依赖冲突可能需要一定的时间和经验,并且需要谨慎操作,避免引入新的问题。在实际操作中,还可以结合使用其他方法,如虚拟环境等,来更好地管理和解决依赖冲突😉。
|
3月前
|
持续交付 Python
如何在Python中自动解决模块和包的依赖冲突?
完全自动解决所有依赖冲突可能并不总是可行,特别是在复杂的项目中。有时候仍然需要人工干预和判断。自动解决的方法主要是提供辅助和便捷,但不能完全替代人工的分析和决策😉。
|
1月前
|
Python
[oeasy]python057_如何删除print函数_dunder_builtins_系统内建模块
本文介绍了如何删除Python中的`print`函数,并探讨了系统内建模块`__builtins__`的作用。主要内容包括: 1. **回忆上次内容**:上次提到使用下划线避免命名冲突。 2. **双下划线变量**:解释了双下划线(如`__name__`、`__doc__`、`__builtins__`)是系统定义的标识符,具有特殊含义。
32 3
|
9月前
|
数据安全/隐私保护 Python
Python3给图片添加水印
Python3给图片添加水印
113 1
|
数据采集 分布式计算 搜索推荐
使用Python实现网页中图片的批量下载和水印添加保存
使用Python实现网页中图片的批量下载和水印添加保存
|
9月前
|
数据安全/隐私保护 Python
python 图片打水印 透明图片合并
python 图片打水印 透明图片合并
77 1
|
9月前
|
数据安全/隐私保护 计算机视觉 Python
如何使用Python给图片添加水印
如何使用Python给图片添加水印
174 0