Python读取txt文件并保存为csv格式

import xlwt
import numpy as np
import os
import re

def read_txt(path):

    filelist = os.listdir(path)
    file_names = np.array([file for file in filelist if file.endswith('.txt')], dtype=object)

    return file_names

workbook = xlwt.Workbook(encoding = 'utf-8')
path = './data_test/predictions_manual'

sheet1 = workbook.add_sheet('result', cell_overwrite_ok=True)
sheet1_row = read_txt(path)
row = 1
for i in range(len(sheet1_row)):
    paths = path + '/' +sheet1_row[i]
    f = open(paths)
    name = paths[31:-4]
    lines = f.readlines()
    for line in lines:
        index = 1
        data = line.strip().split(" ")
        for val in data:
            val = val.split(' ')
            val = [x for x in val if x != '']
            for key in val:
                #key = str(key)
                if index > 3:
                    sheet1.write(row, index, int(key))
                if index == 3:
                    sheet1.write(row, index, float(key))
                if index < 3:
                    sheet1.write(row, index, str(key))
                index += 1
        sheet1.write(row, index, str(name))
        row += 1
workbook.save('test.csv')

写入txt文件部分

                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) ).view(-1).tolist()  # normalized xywh
                        with open(txt_path + '.txt', 'a') as f:
                            #识别类别
                            f.write(str(cfg.textnames[int(cls)])+' ')
                            f.write(str(obj_conf)+' ')
                            f.write(('%g ' * 5 + '\n') % (cls, *xyxy))  # label format
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值