方法一:使用`csv.reader`
```python
import csv
filename = 'E:\\path\\to\\your\\file.csv' 替换为你的文件路径
count = 0
with open(filename, 'r') as f:
csv_reader = csv.reader(f)
for row in csv_reader:
count += 1
print('The total lines is', count)
方法二:使用`pandas.read_csv`
如果你的文件非常大,以至于不能一次性加载到内存中,你可以使用`pandas`的`read_csv`函数,并设置`iterator=True`来分段读取文件。
```python
import pandas as pd
filename = 'E:\\path\\to\\your\\file.csv' 替换为你的文件路径
count = 0
user_info = pd.read_csv(filename, iterator=True)
for chunk in user_info:
count += len(chunk)
print('The total lines is', count)
方法三:使用多线程
如果你有多个CSV文件需要统计行数,并且希望并行处理,可以使用多线程。
```python
import threading
import os
import csv
class MyThreadLine(threading.Thread):
def __init__(self, path):
threading.Thread.__init__(self)
self.path = path
self.line = -1
def run(self):
reader = csv.reader(open(self.path, 'r'))
lines = 0
for item in reader:
lines += 1
self.line = lines
print(self.getName(), self.line)
path = 'C:\\path\\to\\csv\\files' 替换为你的文件所在文件夹路径
filelist = os.listdir(path)
threadlist = []
for filename in filelist:
newpath = os.path.join(path, filename)
mythd = MyThreadLine(newpath)
mythd.start()
threadlist.append(mythd)
for mythd in threadlist:
mythd.join()
linelist = []
for mythd in threadlist:
linelist.append(mythd.line)
print('All lines:', sum(linelist))
以上方法可以帮助你统计CSV文件的行数。请根据你的具体需求选择合适的方法