Python CSV模块:如何在同一个文件中考虑多个表? [英] Python CSV module: How can I account for multiple tables within the same file?

查看:86
本文介绍了Python CSV模块:如何在同一个文件中考虑多个表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个转换为CSV的Excel文件.有几个表,每个表由一个空行分隔.将Excel文件转换为CSV后,我看到每个空行都由一行逗号表示,并且每个列/字段元素都带有一个逗号. CSV模块(或其他Python模块)是否可以根据此信息说明多个表?如果不是,我唯一的选择是在转换之前在Excel中手动将表分成不同的文件吗?

I have an Excel file that I converted to CSV. There are several tables each separated by an empty row. After converting the Excel file to CSV, I see each empty row represented by a row of commas, with a comma for every column/field element. Can the CSV module (or some other Python module) account for multiple tables from this information? If not, is my only option to separate the tables into different files manually in Excel before conversion?

我知道CSV模块会将每一行变成一个列表.我希望表格成为其自己的列表,并将其作为列表包含在其中的所有行.每个表都有第一行作为字段.表格与表格之间的字段可以不同,字段的数量也可以不同.

I know the CSV module will turn each row into a list. I'd like a table to be its own list and all the rows it has as lists within. Each table has the first row as fields. The fields can be different from table to table, and the number of fields can be different as well.

推荐答案

当然,以这种方式读取数据很容易.您必须决定分隔行的构成(检查第一列是否为空是否足够,还是必须检查所有列是否为空?)假设仅第一行(为了清楚起见,还需特别冗长):

Sure, it's easy to read the data in that way. You have to decide what constitutes the separator row (is it sufficient to check for the first column being empty, or do you have to check that all columns are empty?) Assuming just the first row (and being extra verbose for clarity):

 rdr = csv.reader(open(filename))

 tables = []
 this_table = []
 tables.append(this_table)
 for row in rdr:
      if row[0] is None:
         this_table = []
         tables.append(this_table)
      this_table.append(row)

结果是一个称为表的列表.每个条目都是一个列表,其中包含一个表的数据.表中的每个条目都是一个列表,其中包含一行的列值.

The result is a list called tables. Each entry is a list containing the data for one table. Each entry in a table is a list containing the column values for one row.

这篇关于Python CSV模块:如何在同一个文件中考虑多个表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆