简体   繁体   English

Python 3计算CSV中的行数

[英]Python 3 Count number of rows in a CSV

Im having trouble getting the row count in a python 3 environment after migrating from 2.7. 从2.7迁移后,我在python 3环境中无法获取行数。 After several attempts the number of rows returned gives one. 经过几次尝试后,返回的行数为1。 How do I get around a DeprecationWarning: 'U' mode is deprecated in python 3 ? 我该如何避开DeprecationWarning:python 3中不推荐使用'U'模式?

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

In the case of using python 3 Ive tried the following approach but Im still stuck with a 1. 在使用python 3的情况下,Ive尝试了以下方法,但Im仍然坚持使用1。

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

If you are using pandas you can easily do that, without much coding stuff. 如果您使用的是熊猫,则无需太多编码工作即可轻松实现。

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)


input_file = open("test.csv","rb") #rb is a read-in-binary format and 
#you can't count the number of row from binary format file

with open("text.csv",'r') as f:
file = f.readlines()
print(len(file))

# Data in my text file
# a
# b
# c
# d
# e

#The output of above code is 
#5 means number of rows is 5 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM