python3+xlwt 读取txt信息并写入到excel中

# coding = utf-8
import os
import xlwt
import re


def readTxt_toExcel(valueList, Pathlist):
    workbook = xlwt.Workbook()  #
    sheet = workbook.add_sheet('finish_郑磊', cell_overwrite_ok=True)  # Excel单元格名字
    style = xlwt.XFStyle()
    font = xlwt.Font()
    font.name = 'Times New Roman'
    font.bold = True
    # 设置样式的字体
    style.font = font
    title = ["Filepath", "Rect", "右眉毛属性", "右眼属性", "右瞳孔属性", "嘴巴属性", "左眉毛属性", "左眼属性", "左瞳孔属性", "脸颊属性", "表情属性",
             "鼻子属性"]

    '''写入title 信息'''
    col = 0  # 控制列
    for head in title:
        sheet.write(0, col, head, style)
        col += 1
    '''写入 value值以及文件名'''
    hang = 1
    for i in valueList:
        lie = 0
        for value in i:
            sheet.write(hang, lie, value)
            lie += 1
        hang += 1
    h = 1
    for j in Pathlist:
        end_name = j.rfind('.')
        path = str(j[:end_name])
        sheet.write(h, 0, path)  # 导入文件地址
        h += 1
    workbook.save("C:\\Users\\zl3269.ARCSOFT-HZ\\Desktop\\finish_郑磊.xls")

def get_txt_content(file_path):  # 获取文件内容
    Pathlist = []  # 添加文件名列表
    valueList = []  # value 列表
    num = 1
    for path, d, file_list in os.walk(file_path):  # path 原路径下的文件遍历    flie_list 文件下的所有文件
        print(path)
        for filename in file_list:
            if filename.endswith(".txt"):
                with open(path+"\\"+filename, 'r', encoding="utf-8") as f:  # 打开文件 文本的全部路径
                    Pathlist.append(filename)  # 将文件地址添加到列表里
                    # print(txt)
                    items = f.readlines()  # 读取文件,列表格式
                    pattern = re.compile(
                        '.*?name":"(.*?)".*?rect":"(.*?)".*?右眉":"(.*?)".*?右眼":"(.*?)".*?右瞳孔":"(.*?)".*?嘴巴":"(.*?)".*?左眉":"(.*?)"'
                        '.*?左眼":"(.*?)".*?左瞳孔":"(.*?)".*?脸颊":"(.*?)".*?表情":"(.*?)".*?鼻子":"(.*?)"')
                    value = (re.findall(pattern, items[0]))  # 正则匹配需要的字符串
                    # print(type(value))  #[("":"")] 这种类型,所以下面用value[0]获得("":"")并添加到列表,用两个循环调通里面的值
                    # print(value[0])
                    valueList.append(value[0])
                    num += 1
                    print("已处理文件:" + str(num))
                    readTxt_toExcel(valueList, Pathlist)  # 处理txt文件


def main():
    file_path = "F:\\人脸标注\\test_new_20171005\\"
    get_txt_content(file_path)


if __name__ == '__main__':
    main()

猜你喜欢

转载自www.cnblogs.com/zl342423/p/10382583.html