Count how many records are in a CSV Python?

后端 未结 16 1327
无人共我
无人共我 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:40
    import csv
    count = 0
    with open('filename.csv', 'rb') as count_file:
        csv_reader = csv.reader(count_file)
        for row in csv_reader:
            count += 1
    
    print count
    
    0 讨论(0)
  • 2020-11-29 17:40

    I think we can improve the best answer a little bit, I'm using:

    len = sum(1 for _ in reader)
    

    Moreover, we shouldnt forget pythonic code not always have the best performance in the project. In example: If we can do more operations at the same time in the same data set Its better to do all in the same bucle instead make two or more pythonic bucles.

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

    You can also use a classic for loop:

    import pandas as pd
    df = pd.read_csv('your_file.csv')
    
    count = 0
    for i in df['a_column']:
        count = count + 1
    
    print(count)
    
    0 讨论(0)
  • 2020-11-29 17:42

    might want to try something as simple as below in the command line:

    sed -n '$=' filename
    

    or

    wc -l filename
    
    0 讨论(0)
提交回复
热议问题