If I want to get the city of ID=3, which would be Eureka for this
example. Is there a way to do this efficiently instead of iterating
each row? My php code will be executing this python script each time
to get the value, and I feel like being very inefficient to loop
through the csv file every time.
Your ideal solution is to wrap this Python code into an API that you can call from your PHP code.
On startup, the Python code would load the file into a data structure, and then wait for your request.
If the file is very big, your Python script would load it into a database and read from there.
You can then choose to return either a string, or a json object.
Here is a sample, using Flask
:
import csv
from flask import Flask, request, abort
with open('somefile.txt') as f:
reader = csv.DictReader(f, delimiter=',')
rows = list(reader)
keys = row[0].keys()
app = Flask(__name__)
@app.route('/<id>')
@app.route('/')
def get_item():
if request.args.get('key') not in keys:
abort(400) # this is an invalid request
key = request.args.get('key')
try:
result = next(i for i in rows if i['id'] == id)
except StopIteration:
# ID passed doesn't exist
abort(400)
return result[key]
if __name__ == '__main__':
app.run()
You would call it like this:
http://localhost:5000/3?key=city