Reputation: 47
How do I search between the first two commas in a csv file? E.G: CSV FILE:
name, surname, age , gender
How do i only search for the first two, name and surname with the users input?
this is what i have. I am looking for the user to search only by a name or surname:
searchfile = open("python.csv", "r")
a=input()
for line in file:
if a in line:
print(line)
When i do this the user can enter anything that is in the file and it will print the line. I only want to search the first two commas which are name and surname. If the input is not there then reject.
Upvotes: 0
Views: 4144
Reputation: 243
You can use the csv module : it contains an object called a reader, which allows you to split each line of your csv file by defining a delimiter :
import csv
searchfile = open('python.csv', 'rb')
reader = csv.reader(searchfile, delimiter = ',')
a = input()
for row in reader:
if a in row[0] or a in row[1]:
print row
Note that if you're looking for a string in the csv file, you should use raw_input() instead of input() which is only used for numbers.
Upvotes: 1
Reputation: 53285
use csv
import csv
searchfile = open("python.csv", "rb")
reader = csv.reader(searchfile)
for row in reader:
if a in row[0] or a in row[1]:
print row
Upvotes: 0
Reputation: 131
you could split your line
at commas. And then search where ever you want. Something like this:
for line in file: # line = "name, surname, age , gender"
fields = line.split(',') # fields = ["name", " surname" , " age", " gender"]
if a in fields[0] or a in fields[1]:
print(line)
Depending on your future plans, this need no to be the best solution. Also note the leading/trailing white spaces in fields
.
Upvotes: 0