使用python将xls文件转换为csv并将它们保存到一个文件中

时间:2017-12-26 19:28:35

标签: excel python-3.x

我正在尝试将多个.xls文件转换为一个.csv文件,以便我可以在以后的脚本中使用。

我在其他Stackoverflow页面中发现了大部分代码,但在尝试运行下面的代码时出现以下错误:

错误:

Traceback (most recent call last):
  File "script_base_teste.py", line 13, in <module>
    wr.writerow(sh.row_values(rownum))
TypeError: a bytes-like object is required, not 'str'

代码:

import xlrd
import csv


for num in range(1,4):

    wb = xlrd.open_workbook("file"+str(num)+".xls")
    sh = wb.sheet_by_name("Sheet 1")
    your_csv_file = open("file"+str(num)+".csv", "wb")
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in range(0,sh.nrows):
        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()




fout=open("result.csv","a")
first file:
for line in open("file1.csv"):
    fout.write(line)
now the rest:    
for num in range(2,3):
    f = open("file"+str(num)+".csv")
    f.next() # skip the header
    for line in f:
         fout.write(line)
    f.close()
fout.close()

我正在使用Python3,我从thisthis得到了大部分代码

1 个答案:

答案 0 :(得分:0)

您以二进制模式打开文件

your_csv_file = open("file"+str(num)+".csv", "wb")

“wb”代表“写二进制”。 您只能在此模式下读/写二进制数据。 由于您想使用字符串进行编写,因此可以使用“w”而不是“wb”在写入模式下打开它。

your_csv_file = open("file"+str(num)+".csv", "w")
相关问题