2018-10-29 EDIT
Terima kasih atas komentarnya
Saya menguji beberapa jenis kode untuk mendapatkan jumlah baris dalam file csv dalam hal kecepatan. Metode terbaik ada di bawah.
with open(filename) as f:
sum(1 for line in f)
Ini kode yang diuji.
import timeit
import csv
import pandas as pd
filename = './sample_submission.csv'
def talktime(filename, funcname, func):
print(f"# {funcname}")
t = timeit.timeit(f'{funcname}("{filename}")', setup=f'from __main__ import {funcname}', 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)
Hasilnya di bawah.
# 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
Kesimpulannya, sum(1 for line in f)
paling cepat. Tetapi mungkin tidak ada perbedaan yang signifikan dari len(f.readlines())
.
sample_submission.csv
berukuran 30,2MB dan memiliki 31 juta karakter.
file_read
? Apakah itu pegangan file (seperti dalamfile_read = open("myfile.txt")
?