python read and write txt

The following script involves python read and write txt operations. It should be noted that the content to be written when writing data to the text needs to be in the str format. Int, float and other formats will report errors.

#-*- coding: UTF-8 -*-
 
# from PIL import Image
import os
 
 
def get_filelist(path):
    Filelist = []
    for home, dirs, files in os.walk(path):
        for filename in files:
            # 文件名列表,包含完整路径
            if "txt" in filename:
                Filelist.append(os.path.join(home, filename))
            # # 文件名列表,只包含文件名
            # Filelist.append( filename)
 
    return Filelist
 
 
if __name__ == "__main__":
    filePath = './images'
    # 指定保存的文件夹
    outputPath = './imgs_rotate'
    # 获得文件夹下所有文件
    # filePath = './imgs/' # 只能获取当前路径下的文件,不能递归
    # filenames = os.listdir(filePath)
    Filelist = get_filelist(filePath)
    print(len(Filelist))
    # 迭代所有图片
    for filename in Filelist:
        print(filename)
        # 读取图像 标签
        # im = Image.open(filename)
        f = open(filename, encoding='utf-8')
        label = 0
        c_x = 0
        c_y = 0
        width = 0
        height = 0
        for line in f.readlines():
            print(line)
            data = line.replace('\n', '')
            substr = data.split()
            label = substr[0]
            c_x = substr[1]
            c_y = substr[2]
            width = substr[3]
            height = substr[4]
        f.close()
        # 指定逆时针旋转的角度
        # # 逆时针旋转90°
        # tmp = c_x
        # c_x = c_y
        # c_y = str(1 - float(tmp))
        # tmp = width
        # width = height
        # height = tmp
        # line_info = [label, ' ', c_x, ' ',  c_y, ' ', width, ' ', height, '\n']

        # # 逆时针旋转180°
        # c_x = str(1 - float(c_x))
        # c_y = str(1 - float(c_y))
        # line_info = [label, ' ', c_x, ' ', c_y, ' ', width, ' ', height, '\n']
        # 逆时针旋转270°
        tmp = c_x
        c_x = str(1 - float(c_y))
        c_y = tmp
        tmp = width
        width = height
        height = tmp
        line_info = [label, ' ', c_x, ' ', c_y, ' ', width, ' ', height, '\n']
        # 保存
        output_path = filename.replace(filePath, outputPath)
        outputdir = output_path.rsplit('\\', 1)[0]
        if not os.path.exists(outputdir):
            os.mkdir(outputdir)
        file_lineinfo = open(output_path, 'w', encoding='utf-8')
        file_lineinfo.writelines(line_info)
        file_lineinfo.close()

 

 

 

Guess you like

Origin blog.csdn.net/juluwangriyue/article/details/108754908