How to read the first 1000 entries in a csv file

I have a csv file containing 60,000 entries. I read them and saved them in a nested list:

entries = [] with open('mnist_train.csv', 'r') as f: mycsv = csv.reader(f) for row in mycsv: entries.append(row) 

Instead of reading all 60,000, how would I read only the first thousand records?

I tried this without success:

 entries = [] with open('mnist_train.csv', 'r') as f: mycsv = csv.reader(f) for row in mycsv[:1000]: entries.append(row) 
+5
source share
2 answers

As you have discovered, csv.reader does not support slicing. You can use itertools.islice () to accomplish this with objects that are iterable. For instance.

 import itertools entries = [] with open('mnist_train.csv', 'r') as f: mycsv = csv.reader(f) for row in itertools.islice(mycsv, 1000): entries.append(row) 
+3
source

You can use the pandas library-

 import pandas as pd data = pd.read_csv('path/to/your/file.csv',nrows=1000) data_list = data.values.tolist() #creates a list of the first 1000 rows (excludes header) 
0
source

Source: https://habr.com/ru/post/1276093/


All Articles