Python读取tsv文件数据

本文介绍了一个简单的Python程序,用于处理TSV文件。该程序能够读取TSV文件,并将每行数据转换为字典格式,方便进行后续的数据处理和分析工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


"""
create_author : 蛙鳜鸡鹳狸猿
create_time   : 2019-03-19
program       : *_* .tsv file handler *_*
"""

import codecs


class TSV(object):
    """
    .tsv file's handler.
    """

    def __init__(self, file):
        """
        TSV init.
        :param file: .tsv file to handle.
        """
        self.file = file

    def __repr__(self):
        return "File {file} under handling......".format(file=self.file)

    def tsv(self):
        """
        .tsv file's column definition and data check.
        :return: List.
            lines data from [file] row by row in dict format.
        """
        with codecs.open(self.file, 'r', "utf-8") as f:
            line = f.readline()
            data = []
            head = []
            while line:
                if line.isspace():
                    line = f.readline()
                    continue
                elif not line.isspace():
                    # to be compatible between OS
                    head = line.rstrip("\r\n").split('\t')
                    line = f.readline()
                    break
            while line:
                if line.isspace():
                    line = f.readline()
                    continue
                elif not line.isspace():
                    body = line.rstrip("\r\n").split('\t')
                    rows = zip(head, body)
                    tsv_dic = {}
                    for (head_sub, body_sub) in list(rows):
                        tsv_dic[head_sub] = body_sub
                    data.append(tsv_dic)
                    line = f.readline()
            return data


if __name__ == "__main__":
    with codecs.open("tsv", 'w', "utf-8") as f:
        rows = """


        Id\tContent
        1\tContent1
        2\tContent2
        3\tContent3
        4\tContent4


        1024\tContent1024

        """
        f.writelines(rows.replace(' ', ''))
    TSV_Tester = TSV(file="tsv")
    print(TSV_Tester.tsv())

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值