xls文件解析及数据入库

该博客介绍了如何使用Python的open方法读取CSV文件,通过迭代器处理数据,并检查表头的合理性。内容包括读取文件的前五行,判断列数是否一致,将表头写入内存,并进行一定的文件操作,如生成新的CTL文件和执行loader脚本。
摘要由CSDN通过智能技术生成

包括内容: 1、读取文件数据(open方法)

2、Python的迭代器使用   

3、文件的写入 

4、判断表头是否合理

    # xjy_create
    # 读取csv文件
    line_length = 0
    with open(filename, 'r')as read_csv:
        print("open filename as read_csv")
        # 读取5行数据
        lines = read_csv.readlines(5)
        flag = True  # 创建一个判断值:True or False

    # 创建一个迭代器
    for index in range(len(lines)):
        line = lines[index].split(',')  # 将每一行从 str -> list
        if index == 0:
            line_length = len(line)  # 每一行的元素个数
            print ("====line_length is:===")
            print line_length
        else:
            if line_length != len(line):
                flag = False
                break
    # 判断是一个合理的表格: 表头每一列个数都相同
    if flag:
        print ("if flag == True")
        # 将表头存入内存
        file_header = "/home/liuyy/dataImport/data/" + str(user_id) + " " + tbname + ".ctl"
        with open(filename, 'r')as read_csv:
            with open(file_header, 'w') as store_header:
                print ("===store table_header===")
                # 读取csv文件前五行  并写入内存
                test_line = 0
                for line in read_csv.readlines():
                    test_line = test_line + 1
                    # print line
                    if test_line <= 5:
                        store_header.write(line)
                    else:
                        break

        # 入库操作
        with open("/home/liuyy/dataImport/dataImport/loader_new.sh", 'r')as f_in:
            print ("===loader_new.sh===")
            with open(file4, 'w')as f_out:
                for line in f_in.readlines():
                    print ("****loader.sh : line***")
                    print line
                    if line.find("[ctl]") >= 0 or line.find("[log]") >= 0:
                        f_out.write(line.replace("[ctl]", file1).replace("[log]", log))
                    else:
                        f_out.write(line)

    # xjy_create_end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值