Python系列(3)-- Python 读取EXCEL(XLS、CSV)写入txt文件

本人尝试了很多网上的方法,发现下面这些不同的错误
TypeError: a bytes-like object is required, not ‘str’

UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa2 in position 50: illegal multibyte sequence

UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xde in position 16: invalid continuation byte
至今无法解决,无意间发现之前自己写的代码解决了我的问题:

# -*- coding: utf-8 -*-
"""
Created on Wed Sep 27 19:41:35 2017

@author: Don
"""
import numpy as np  
import xlrd                             #打开excel文件  
data = xlrd.open_workbook('gd-2.xls')   #打开Excel文件读取数据  
sh = data.sheet_by_name("sheet1")       #通过工作簿名称获取(excel下面的表单)
print(sh.nrows)                         #行数   
print(sh.ncols)                         #列数   
n=0  
i=0  
file=open("gd-2.txt","w")
for n in range(sh.nrows):
    text1 = sh.cell_value(n, 1)             //读取指定列  我要读取第二列
    text2 = sh.cell_value(n, 2)             //读取指定列  我要读取第三列
    text4 = sh.cell_value(n, 4)             //读取指定列  我要读取第五列
    file.write(text1)
    file.write("\t")
    file.write(text2)
    file.write("\t")
    file.write(text4)
    file.write("\t")
    file.write('\n')

#    for i in range(sh.ncols):           //遍历读取每一列
#        text=sh.cell_value(n,i)
#        file.write(text)   
#        file.write('\n')

file.close()

你可能感兴趣的:(python)