Count how many records are in a CSV Python?

后端 未结 16 1326
无人共我
无人共我 2020-11-29 16:43

I\'m using python (Django Framework) to read a CSV file. I pull just 2 lines out of this CSV as you can see. What I have been trying to do is store in a variable the total n

相关标签:
16条回答
  • 2020-11-29 17:30
    numline = len(file_read.readlines())
    
    0 讨论(0)
  • 2020-11-29 17:31

    row_count = sum(1 for line in open(filename)) worked for me.

    Note : sum(1 for line in csv.reader(filename)) seems to calculate the length of first line

    0 讨论(0)
  • 2020-11-29 17:34

    when you instantiate a csv.reader object and you iter the whole file then you can access an instance variable called line_num providing the row count:

    import csv
    with open('csv_path_file') as f:
        csv_reader = csv.reader(f)
        for row in csv_reader:
            pass
        print(csv_reader.line_num)
    
    0 讨论(0)
  • 2020-11-29 17:35

    You need to count the number of rows:

    row_count = sum(1 for row in fileObject)  # fileObject is your csv.reader
    

    Using sum() with a generator expression makes for an efficient counter, avoiding storing the whole file in memory.

    If you already read 2 rows to start with, then you need to add those 2 rows to your total; rows that have already been read are not being counted.

    0 讨论(0)
  • 2020-11-29 17:35
    import pandas as pd
    data = pd.read_csv('data.csv') 
    totalInstances=len(data)
    
    0 讨论(0)
  • 2020-11-29 17:38

    try

    data = pd.read_csv("data.csv")
    data.shape
    

    and in the output you can see something like (aa,bb) where aa is the # of rows

    0 讨论(0)
提交回复
热议问题