[Python]读取二进制文件

版权声明:转载请说明Zhonglihao原创 https://blog.csdn.net/xeonmm1/article/details/84869969
import os
import xlwt

path = os.path.split(os.path.realpath(__file__))[0]                  # 设置路径
print(path)                                                          # 获取指定路径下的文件
dirs = os.listdir(path)
k = -1 # xls行号

# 新建一个xls存放结果
workbook = xlwt.Workbook(encoding='utf-8')
booksheet = workbook.add_sheet('Sheet 1', cell_overwrite_ok=True)
out_put_file_name = "detail.xls"

# 读取目录下的txt文件
for txt_file in dirs:  

    if os.path.splitext(txt_file)[1] == ".txt":                     # 筛选txt文件
        print(txt_file)                                             # 输出所有的txt文件
        file_dir = path + "\\"+ txt_file   

        # 获取文件的大小 Byte
        f = open(file_dir,"rb")
        file_size = os.path.getsize(file_dir)

        # 分别存入
        for i in range(1,file_size+1):
            data = f.read(1) # 一个byte
            data = ord(data) # 转换为十进制
            data = str(data) # 转换为字符串
        f.close()

        k = k + 1
        booksheet.write(k,0,xxxx) # 写处理到xls文件
        
workbook.save(out_put_file_name)

猜你喜欢

转载自blog.csdn.net/xeonmm1/article/details/84869969