How do quickly search through a .csv file in Python

后端 未结 6 986
别跟我提以往
别跟我提以往 2020-12-18 09:10

I\'m reading a 6 million entry .csv file with Python, and I want to be able to search through this file for a particular entry.

Are there any tricks to search the en

6条回答
  •  长情又很酷
    2020-12-18 09:53

    If the csv file isn't changing, load in it into a database, where searching is fast and easy. If you're not familiar with SQL, you'll need to brush up on that though.

    Here is a rough example of inserting from a csv into a sqlite table. Example csv is ';' delimited, and has 2 columns.

    import csv
    import sqlite3
    
    con = sqlite3.Connection('newdb.sqlite')
    cur = con.cursor()
    cur.execute('CREATE TABLE "stuff" ("one" varchar(12), "two" varchar(12));')
    
    f = open('stuff.csv')
    csv_reader = csv.reader(f, delimiter=';')
    
    cur.executemany('INSERT INTO stuff VALUES (?, ?)', csv_reader)
    cur.close()
    con.commit()
    con.close()
    f.close()
    

提交回复
热议问题