首页 > 解决方案 > Python 3 计算 CSV 中的行数

问题描述

从 2.7 迁移后,我无法在 python 3 环境中获取行数。几次尝试后,返回的行数为 1。如何绕过 DeprecationWarning: 'U' mode is deprecated in python 3 ?

             input_file = open("test.csv","rU")
             reader_file = csv.reader(input_file)
             value = len(list(reader_file))

在使用 python 3 的情况下,我尝试了以下方法,但我仍然坚持使用 1。

             input_file = open("test.csv","rb")
             reader_file = csv.reader(input_file)
             value = len(list(reader_file))

标签: pythonpython-3.xcsvmigration

解决方案


如果您使用的是 pandas,您可以轻松做到这一点,而无需太多编码内容。

import pandas as pd

df = pd.read_csv('filename.csv')

## Fastest would be using length of index

print("Number of rows ", len(df.index))

## If you want the column and row count then

row_count, column_count = df.shape

print("Number of rows ", row_count)
print("Number of columns ", column_count)



推荐阅读