[文件] Python读取txt存储至xls

目录


需求

以行列号命名的.txt,存储着该网格内的wifi信号
.txt命名格式:行号_列号.txt

.txt内容:

代码

# coding:utf8
import os
import xlwt

input_dir = r'F:\study\school\Android\kczx\lab4\data' #文件夹需要删除index.txt
save_dir = r'F:\study\school\Android\kczx\lab4\data'
# 起始行列号
x0 = 27
y0 = 15

if __name__ == '__main__':
    # 获取文件名
    filenames = os.listdir(input_dir)
    # 存储数据
    data = {}
    # 遍历文件
    for filename in filenames:
        # 得到行列号
        x,y = filename[0:5].split('_')
        x,y = int(x)-x0,int(y)-y0
        # 读取数据
        file_path = os.path.join(input_dir,filename)
        f = open(file_path,'r')
        while True:
            line = f.readline()
            if not line:
                break
            line_datas = line.split('#')
            if len(line_datas)!=6:
                continue
            if not data.has_key(line_datas[0]):
                data[line_datas[0]] = []
            data[line_datas[0] ].append(
                {
                    "x" : x,
                    "y" : y,
                    "info" : line_datas[4]
                }
            )
        f.close()

    print data
    # 一个mac存储成一个xls
    for (mac,value) in data.items():
        wb = xlwt.Workbook()
        sheet = wb.add_sheet(mac)
        for item in value:
            print item
            sheet.write(
                item['x'],
                item['y'],
                item['info']
            )
        wb.save(os.path.join(save_dir,mac+'.xls'))

转载自:https://blog.csdn.net/summer_dew/article/details/79735750

You may also like...

退出移动版