Посчитайте, сколько строк в CSV Python?
Я использую python (Django Framework) для чтения CSV файла. Я вытаскиваю только 2 строки из этого CSV, как вы можете видеть. То, что я пытался сделать, это сохранить в переменной общее количество строк CSV. Как получить общее количество строк?
file = object.myfilePath fileObject = csv.reader(file) for i in range(2): data.append(fileObject.next())
len(fileObject) fileObject.length
11 ответов
Вам нужно подсчитать количество строк:
row_count = sum(1 for row in fileObject) # fileObject is your csv.reader
Использование sum() с выражением генератора делает эффективный счетчик, избегая хранения всего файла в памяти.
Если вы уже прочитали 2 строки для начала, вам нужно добавить эти 2 строки в общую сумму; строки, которые уже были прочитаны, не учитываются.
Вы должны прочитать строки; не гарантируется, что строки имеют фиксированный размер, поэтому единственный способ подсчитать их — это прочитать их все.
это странно, потому что у меня есть файл с более чем 4,5 миллионами строк, и этот метод насчитывает только 53 строки .
@Escachator: на какой ты платформе? Есть ли в файле символы EOF ( CTRL-Z, \x1A )? Как вы открыли файл?
Я делаю следующее: file_read = csv.reader (‘filename’) row_count = sum (1 для строки в file_read) Не думайте, что в файле есть EOF, только чистые цифры «,» и \ n
@Escachator: тогда ваше имя файла содержит 53 символа. Читатель берет итеративный или открытый файловый объект, но не имя файла.
теперь это работает, и это супер быстро! Я сделал: file_read = open (‘filename’) row_count = sum (1 для строки в file_read) большое спасибо!
Обратите внимание, что если вы хотите снова выполнить итерацию в считывателе (скажем, для обработки строк), вам нужно будет сбросить итератор и воссоздать объект считывателя: file.seek(0) затем fileObject = csv.reader(file)
РЕДАКТИРОВАТЬ 2018-10-29
Я протестировал несколько видов кода, чтобы получить количество строк в CSV файле с точки зрения скорости. Лучший метод ниже.
with open(filename) as f: sum(1 for line in f)
import timeit import csv import pandas as pd filename = './sample_submission.csv' def talktime(filename, funcname, func): print(f"# ") t = timeit.timeit(f'("")', setup=f'from __main__ import ', number = 100) / 100 print('Elapsed time : ', t) print('n = ', func(filename)) print('\n') def sum1forline(filename): with open(filename) as f: return sum(1 for line in f) talktime(filename, 'sum1forline', sum1forline) def lenopenreadlines(filename): with open(filename) as f: return len(f.readlines()) talktime(filename, 'lenopenreadlines', lenopenreadlines) def lenpd(filename): return len(pd.read_csv(filename)) + 1 talktime(filename, 'lenpd', lenpd) def csvreaderfor(filename): cnt = 0 with open(filename) as f: cr = csv.reader(f) for row in cr: cnt += 1 return cnt talktime(filename, 'csvreaderfor', csvreaderfor) def openenum(filename): cnt = 0 with open(filename) as f: for i, line in enumerate(f,1): cnt += 1 return cnt talktime(filename, 'openenum', openenum)
# sum1forline Elapsed time : 0.6327946722068599 n = 2528244 # lenopenreadlines Elapsed time : 0.655304473598555 n = 2528244 # lenpd Elapsed time : 0.7561274056295324 n = 2528244 # csvreaderfor Elapsed time : 1.5571560935772661 n = 2528244 # openenum Elapsed time : 0.773000013928679 n = 2528244
В заключение, sum(1 for line in f) является самой быстрой. Но может не быть существенного отличия от len(f.readlines()) .
sample_submission.csv sample_submission.csv имеет sample_submission.csv МБ и 31 миллион символов.
Python: Count the number of lines in a given CSV file
Step1 — Open the CSV file using the open(«employees.csv»).
Step2 — Create a CSV reader by calling the function csv.reader(reader) as the result of the previous step.
Step3 — Get a list representation of the CSV file by calling list(reader) of the previous step.
Step4 — Count the number of lines in the CSV file with len(list(reader)).
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource’s quiz.
Follow us on Facebook and Twitter for latest update.
Python: Tips of the Day
How to delete a file or folder?
- os.remove() removes a file.
- os.rmdir() removes an empty directory.
- shutil.rmtree() deletes a directory and all its contents
Path objects from the Python 3.4+ pathlib module also expose these instance methods:
- pathlib.Path.unlink() removes a file or symbolic link.
- pathlib.Path.rmdir() removes an empty directory.
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook
6 Python snippets to find number of lines from a CSV file — Basics to Pandas
There are multiple ways one can find number of records from CSV file using Python. This article describes 6 different ways and explores the performant method to bridges to distributed computing using Pandas and Koalas
While I am writing the article “Split a large CSV file randomly or equally into smaller files”, I used couple of methods to find number of lines in a given file. That brought me into curiosity to see best method to find number of lines in given file.
Lets go through 6 different methods (there could be more ways to solve this), these all are basic methods anyone can understand and utilize.
Method1: Count number of records using python enumerate and loop
In this method, first open the the file in read mode and loop through enumerated file content, when the loop completes last iteration consists of line_count
def count_lines_enumrate(file_name):
fp = open(file_name,'r')
for line_count, line in enumerate(fp):
pass
return line_count
Method2: Count number of records using python enumerate and list
In this method, first open the file in read mode and convert enumerated result to a list and extract last element of the list
def count_lines_enumrate(file_name):
fp = open(file_name,'r')
line_count = list(enumerate(fp))[-1][0]
return line_count
Method3: Count number of records using python sum 1 for every line
In this method, open the file in read mode and sum function just like list comprehension
def count_line_sum(file_name):
fp = open(file_name,'r')
line_count = sum(1 for line in fp)
return line_count
Method4: Count number of records using file method read lines
In this method, open the file in read mode and length of the list generated by read lines file method
def count_lines_readlines(file_name):
fp = open(file_name,'r')
line_count = len(fp.readlines())
return line_count
Method5: Count number of records using basic python using counting lines