Reputation: 19
I'm trying to run a code that can read a specific line of data from a csv file in python.
import csv
with open('details.csv', 'rt') as f:
reader = csv.reader(f)
selected_details = input("Enter student ID for details:\n")
for selected_details in reader:
print(reader)
How could I take an input and then use that to select and print that specific row?
Upvotes: 0
Views: 7346
Reputation: 1870
You could use next
with a default value.
This will return the first row where the idx
index equals value
or None
if it is not found:
import csv
def find_by_position(filename, idx, value):
with open(filename) as f:
reader = csv.reader(f)
row = next((item for item in reader if item[idx] == value), None)
return row
Sample usage:
>>> # `data/data.csv` looks like this:
... #
... # id,name,score
... # 1,bla,65
... # 5,another name,95
... # 9,test,95
...
>>> find_by_position('data/data.csv', 0, '5')
['5', 'another name', '95']
>>> find_by_position('data/data.csv', 1, 'bla')
['1', 'bla', '65']
A more descriptive approach would be to use csv.DictReader
so that we can search based on the column name:
import csv
def find_by_column(filename, column, value):
with open(filename) as f:
reader = csv.DictReader(f)
row = next((item for item in reader if item[column] == value), None)
return row
Usage is very similar to the previous approach:
>>> # `data/data.csv` looks like this:
... #
... # id,name,score
... # 1,bla,65
... # 5,another name,95
... # 9,test,95
...
>>> find_by_column('data/data.csv', 'id', '5')
OrderedDict([('id', '5'), ('name', 'another name'), ('score', '95')])
>>> find_by_column('data/data.csv', 'name', 'bla')
OrderedDict([('id', '1'), ('name', 'bla'), ('score', '65')])
Upvotes: 3
Reputation: 359
A filter should do the trick, something like
import csv
with open('details.csv', 'rt') as f:
reader = csv.reader(f)
selected_details = input("Enter student ID for details:\n")
results = filter(lambda x: selected_details in x, reader)
for line in results:
print(line)
Filter take an itterable (here reader) and will apply for each element of the itterable the lambda you give him and will return a new list "filtered". If the lambda return True the element will be returned in the filtered list.
A lambda is basically a dwarf-function (wiser, nerdier people will correct me on this over simplification but you get the idea) that return the one and only line you gave him.
So my lambda just does the operation "selected_details in x" that will return True if selected_details is in x and else False, you get the idea.
Upvotes: 1
Reputation: 82765
You can iterate over each line and check if the user inputted data is in line.
Ex:
import csv
selected_details = input("Enter student ID for details:\n")
with open('details.csv', 'rt') as f:
reader = csv.reader(f)
for line in reader:
if selected_details in line:
print(reader)
break
Upvotes: 2