在python中使用csv模块阅读.xlsx [英] Read in .xlsx with csv module in python
问题描述
我正在尝试使用 csv
模块读取.xlsx格式的excel文件,但是当使用excel文件时,我没有运气甚至用我的方言和编码指定。下面我用不同的编码显示了不同的尝试和错误结果。如果有任何人可以指出我正确的编码,语法或模块,我可以使用Python读取.xlsx文件,我会很感激。
I'm trying to read in an excel file with .xlsx formatting with the csv
module, but I'm not having any luck with it when using an excel file even with my dialect and encoding specified. Below, I show my different attempts and error results with the different encodings I tried. If anyone could point me into the correct coding, syntax or module I could use to read in a .xlsx file in Python, I'd appreciate it.
使用以下代码,我收到以下错误: _csv.Error:行包含NULL字节
With the below code, I get the following error: _csv.Error: line contains NULL byte
#!/usr/bin/python
import sys, csv
with open('filelocation.xlsx', "r+", encoding="Latin1") as inputFile:
csvReader = csv.reader(inputFile, dialect='excel')
for row in csvReader:
print(row)
使用以下代码,我收到以下错误: UnicodeDecodeError:'utf-8'编解码器无法解码位置16的字节0xcc:无效的连续字节
With the below code, I get the following error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcc in position 16: invalid continuation byte
#!/usr/bin/python
import sys, csv
with open('filelocation.xlsx', "r+", encoding="Latin1") as inputFile:
csvReader = csv.reader(inputFile, dialect='excel')
for row in csvReader:
print(row)
当我在编码$ c中使用
utf-16
$ c>,我收到以下错误: Un icodeDecodeError:'utf-16-le'编解码器无法解码位置570-571中的字节:非法UTF-16代理
When I use utf-16
in the encoding
, I get the following error: UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 570-571: illegal UTF-16 surrogate
推荐答案
您不能使用Python的 csv
库来阅读 xlsx
格式的文件。您需要安装和使用不同的库。例如,您可以使用 xlrd
,如下所示:
You cannot use Python's csv
library for reading xlsx
formatted files. You need to install and use a different library. For example, you could use xlrd
as follows:
import xlrd
workbook = xlrd.open_workbook("filelocation.xlsx")
sheet = workbook.sheet_by_index(0)
for rowx in range(sheet.nrows):
cols = sheet.row_values(rowx)
print(cols)
将文件中的所有行显示为列的列表。 Python Excel 网站提供了其他可能的示例。
This would display all of the rows in the file as lists of columns. The Python Excel website gives other possible examples.
这篇关于在python中使用csv模块阅读.xlsx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!