还是 Python 的新手,这是我已经取得的成就:
import csv
import sys
import os.path
#VARIABLES
reader = None
col_header = None
total_rows = None
rows = None
#METHODS
def read_csv(csv_file):
#Read and display CSV file w/ HEADERS
global reader, col_header, total_rows, rows
#Open assign dictionaries to reader
with open(csv_file, newline='') as csv_file:
#restval = blank columns = - /// restkey = extra columns +
reader = csv.DictReader(csv_file, fieldnames=None, restkey='+', restval='-', delimiter=',',
quotechar='"')
try:
col_header = reader.fieldnames
print('The headers: ' + str(reader.fieldnames))
for row in reader:
print(row)
#Calculate number of rows
rows = list(reader)
total_rows = len(rows)
except csv.Error as e:
sys.exit('file {}, line {}: {}'.format(csv_file, reader.line_num, e))
def calc_total_rows():
print('\nTotal number of rows: ' + str(total_rows))
我的问题是,当我尝试计算行数时,结果为 0(不可能,因为 csv_file 包含 4 行并且它们打印在屏幕上。 我将“#Calculate number of rows”代码放在我的打印行循环上方并且它可以工作,但是这些行然后不打印。好像每个任务都在互相偷字典?我该如何解决这个问题?
最佳答案
问题在于 reader
对象在遍历 CSV 时表现得像一个文件。首先,您在 for
循环中进行迭代,并打印每一行。然后你尝试从剩下的内容创建一个列表——当你遍历整个文件时它现在是空的。这个空列表的长度是0。
试试这个:
rows = list(reader)
for row in rows:
print(row)
total_rows = len(rows)
关于python - 使用 DictReader 计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21539460/