【问题标题】:Python 3 Count number of rows in a CSVPython 3 计算 CSV 中的行数
【发布时间】:2019-10-19 12:28:50
【问题描述】:

从 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))

【问题讨论】:

  • "rb" 中删除"b"
  • 仍然给我一个 1
  • 您能分享您的 CSV 文件的摘录吗?
  • >>> len(list(csv.reader(open(r'new.csv')))) 为我工作。您的文件只有一行。

标签: python python-3.x csv migration


【解决方案1】:

如果您使用的是 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)


【讨论】:

  • 好多了,虽然我还差一排
  • 如果您执行 read_csv 并且跳过了错误的行,有没有办法在读取后获取原始 CSV 和数据框中的行数?
【解决方案2】:
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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    相关资源
    最近更新 更多