我正在编写一个程序,该程序从CSV中获取数据并将其转换为表格以导出为PDF。我正在使用的CSV有一堆空行,所以当我在Python中创建我的Matrix时,我有一堆空行。我想删除所有以''开头的行。我写的代码是:
i=0
x=rows-empty ##where empty has been defined and the number of rows I need to delete.
for i in range(x):
if Matrix[i][0] == '':
del Matrix[i]
i+=1
我遇到的问题是,如果有两个连续的空行,则只删除一行。关于如何摆脱这两条线的任何想法?
我使用以下代码创建并填充Matrix:
##creates empty matrix
with open(filename) as csvfile:
serverinfo=csv.reader(csvfile, delimiter=",", quotechar="|")
rows=0
for row in serverinfo:
NumColumns = len(row)
rows += 1
Matrix=[[0 for x in xrange(9)] for x in xrange(rows)]
csvfile.close()
##fills Matrix
with open(filename) as csvfile:
serverinfo=csv.reader(csvfile, delimiter=",", quotechar="|")
rows=0
for row in serverinfo:
colnum = 0
for col in row:
Matrix[rows][colnum] = col
if col==0:
del col
colnum += 1
rows += 1
csvfile.close()
答案 0 :(得分:0)
不要在之后删除它们,只是不要加载它们开始。您还可以快速重新读取文件两次,因为看起来您的列限制为9
,因此对于每一行,只需将0
填充到该大小即可。 ..例如:
import csv
from itertools import chain, islice, repeat
COLS = 9 # or pre-scan file to get max columns
FILL_VALUE = 0 # or None, or blank for instance
with open(filename) as fin:
csvin = csv.reader(fin) # use appropriate delimiter/dialect settings
non_blanks = (row for row in csvin if row[0]) # filter out rows with blank 1st col
matrix = [list(islice(chain(row, repeat(FILL_VALUE)), COLS)) for row in non_blanks]
根据您对数据的处理方式,您可能还希望查看numpy
模块和可用的loadtxt()
方法。