我是一个Python新手,所以这可能听起来像一个愚蠢的问题,但我有一个CSV文件,我希望我的脚本打印文件中的行数和列数。这是我的剧本:
import csv
op = open(Test06242015.csv)
rd = csv.reader(op)
for row in rd:
list = []
list.append(row)
print list
for items in row:
print len(row)
op.close()
我实际上得到了正确答案(320),但每行打印出320次(下方):
[['19.385', '19.227', '18.308', ...]]
320
320
320
320
320
320
320
320
(...and it keeps going)
如何制作320只打印一次?另外,我怎样才能读取行数?
非常感谢!
答案 0 :(得分:2)
您正在内循环内打印行的长度,尝试将其打印在内循环之外。
示例 -
for row in rd:
list = []
list.append(row)
print list
for items in row:
pass # or whatever other logic you want, if you do not want to do anything remove this loop
print len(row)
答案 1 :(得分:0)
import csv
with open('Test06242015.csv', 'rb') as f:
reader = csv.reader(f)
line = next(reader, [])
remaining = len(reader)
print len(line) # Number of columns
if line:
remaining += 1
print remaining # Total numer of rows.
答案 2 :(得分:0)
您应该只打印行及其长度,而不是每行的整个列表和每列的行长度。
counter = 1
for row in rd:
print counter, len(row), row
counter += 1
答案 3 :(得分:0)
你也可以使用大熊猫快速获取你需要的信息:
import pandas as pd
df = pd.read_csv('filename.csv')
print(df.shape)
#Output
#(数字或行数,列数)