I have a .csv file with about 1000 rows which looks like:
id,first_name,last_name,email,gender,ip_address,birthday 1,Ced,Begwell,cbegwell0@google.ca,Male,134.107.135.233,17/10/1978 2,Nataline,Cheatle,ncheatle1@msn.com,Female,189.106.181.194,26/06/1989 3,Laverna,Hamlen,lhamlen2@dot.gov,Female,52.165.62.174,24/04/1990 4,Gawen,Gillfillan,ggillfillan3@hp.com,Male,83.249.190.232,31/10/1984 5,Syd,Gilfether,sgilfether4@china.com.cn,Male,180.153.199.106,11/07/1995
What I have for code so far will ask for input, then go over each row and print the row if it contains the input. Looks like so:
import csv # Asks for search criteria from user search = input("Enter search criteria:\n") # Opens csv data file file = csv.reader(open("MOCK_DATA.csv")) # Go over each row and print it if it contains user input. for row in file: if search in row: print(row)
What I want for end result, and what I'm stuck on, is to be able to enter more that one search criteria seperated by a "," and it will search and print those rows. Kind of like a way to filter the list.
for expample if there was multiple "David" that are "Male" in the file. I could enter : David, Male
It would then print all the rows that match but ignore those with a "David" thats is "Female".
score:0
If you are happy to use a 3rd party library, this is possible with pandas
.
I have modified your data slightly to demonstrate a simple query.
import pandas as pd
from io import StringIO
mystr = StringIO("""id,first_name,last_name,email,gender,ip_address,birthday
1,Ced,Begwell,cbegwell0@google.ca,Male,134.107.135.233,17/10/1978
2,Nataline,Cheatle,ncheatle1@msn.com,Female,189.106.181.194,26/06/1989
3,Laverna,Hamlen,lhamlen2@dot.gov,Female,52.165.62.174,24/04/1990
4,David,Gillfillan,ggillfillan3@hp.com,Male,83.249.190.232,31/10/1984
5,David,Gilfether,sgilfether4@china.com.cn,Male,180.153.199.106,11/07/1995""")
# replace mystr with 'file.csv'
df = pd.read_csv(mystr)
# retrieve user inputs
first_name = input('Input a first name\n:')
gender = input('Input a gender, Male or Female\n:')
# calculate Boolean mask
mask = (df['first_name'] == first_name) & (df['gender'] == gender)
# apply mask to result
res = df[mask]
print(res)
# id first_name last_name email gender \
# 3 4 David Gillfillan ggillfillan3@hp.com Male
# 4 5 David Gilfether sgilfether4@china.com.cn Male
# ip_address birthday
# 3 83.249.190.232 31/10/1984
# 4 180.153.199.106 11/07/1995
score:0
While you could just check if the strings "David"
and "Male"
exist in a row, it would not be very precise should you need to check column values. Instead, read in the data via csv
and create a list of namedtuple
objects that store the search value and header name:
from collections import namedtuple
import csv
data = list(csv.reader(open('filename.csv')))
search = namedtuple('search', 'value,header')
searches = [search(i, data[0].index(b)) for i, b in zip(input().split(', '), ['first_name', 'gender'])]
final_results = [i for i in data if all(c.value == i[c.header] for c in searches)]
score:1
You can split the input on the comma then check to make sure each field from the input is present on a given line using all()
and list comprehensions.
This example uses a simplistic splitting of the input, and doesn't care which field each input matches. If you want to only match to specific columns, look into using csv.DictReader
instead of csv.reader
.
import csv
# Asks for search criteria from user
search_parts = input("Enter search criteria:\n").split(",")
# Opens csv data file
file = csv.reader(open("MOCK_DATA.csv"))
# Go over each row and print it if it contains user input.
for row in file:
if all([x in row for x in search_parts]):
print(row)
Credit To: stackoverflow.com
Related Query
- How to search CSV file with multiple search criteria and print row?
- How to search for word in text file and print part of line with Python?
- How to search for word in text file and print the entire line with Python?
- How to print out row of CSV file with max value in one column Python
- How can I search a list in python and print at which location(s) in that list my criteria is located?
- How to Calculate Average Time between Dates in CSV File with multiple column in Python?
- Python Regex: How do I use regular expression to read in a file with multiple lines, and extract words from each line to create two different lists
- Scrapy CSV header row format with Multiple spiders and CSVItemExporter
- How can I print the required row when reading a csv file in python
- How to convert CSV file which having both comma and space delimiter to csv with only space delimiter
- How to parse huge XML with Python and XSLT file iteratively and write to CSV
- How to parse a CSV file as with commas or pipes and read into a data frame?
- how can i search a text file of list of words from user input and print the line which contains these words?
- How do I format a csv file (such as omitting first row and column) without modules?
- How can I pass all the variables as a list and download multiple csv with few lines of code instead of several lines?
- how to upload images from csv file that have column with labels and urls of images in Azure machine learning by code
- How to make Python search through a text file and print every matching line?
- How to print multiple values from multiple array/list with string in front of first output only and comma separation between values?
- How do I Import a csv file containing repeated lines of information (blocks) whereby for example a row beginning with 'T' refers to time etc
- How to copy CSV file with 50000 rows and a header to another CSV,with some conditions?
- How can I read in a file with multiple x, y coordinates pairs and display as scatter points in Python 3
- How to read a file and print lines with only a certain amount of digits
- How to print those words that a .txt / .py file has and does not have another .txt / .py file with which I compare it?
- How to use strings from one text file to search another, and create a new text file with columns from another?
- How to read and write INI file with Python3?
- How to print multiple lines of text with Python
- How to print a list with integers without the brackets, commas and no quotes?
- how to print directly to a text file in both python 2.x and 3.x?
- How to print multiple non-consecutive values from a list with Python 3.5.1
- How do I print only the first 10 lines from a csv file using Python?
- How to find out the file extension for extracting audio tracks with ffmpeg and python?
- How to read only a specific range of lines out of a csv file with python?
- Python edit specific row and column of csv file
- Where do I put the .so file from Boost.Python so I can import it as a module, and how do I use it with both Python 2 and 3
- How to use GridSearchCV for comparing multiple models along with pipeline and hyper-parameter tuning in python
- How to download zip file and parse csv file from it in python
- SQLAlchemy and mssql : how to create unique constraint with multiple null value
- How to scrape JSON file from url and print contents
- How to print character from a specific character to a specific character with multiple instances of the character?
- How to open a file with a known encoding on both Python2 and 3?
- how to print ones and zeros in columns with their indexes in python?
- How to find duplicates in a csv column, and remove any row that doesn't have a duplicate
- How to write a new row in an existing csv file without appending it in the last line?
- How to use UDP with Asyncio for multiple file transfer from server to client - python
- How to delete parts of XML data and write it to a new file with Python
- How do I convert a csv file with one column to a dictionary in Python?
- How to process uploaded csv file from web form with Python 3?
- Python: How to go through a file and replace curse words with a "censored"
- How to import data from a CSV file and store it in a variable?
- How to search and replace with enclosed characters a text file?
More Query from same tag
- Interpreter-style output in Python 3 (maybe about sys.displayhook?)
- Python importing module that imports another module
- python: replace elements in list with conditional
- Missing column headers in saved file
- Caesar Cipher code only Ciphers one letter not entire string
- Installing pyephem or astropy on Pyzo
- Dynamically adding a row in data table Kivy/KivyMD
- Why is comma separator returning me a comma once I print it?
- I wonder how is second 'return' works - return len(A) + 1
- Python 3.6 TypeError: string indices must be integers when trying to send office 365 email
- How to update a ColumnDataSource data for a MultiLine glyph?
- how to filter a numbers list in Python 3 inside a loop & change list length
- Concerned about malicious libraries in my project
- a class with all static methods
- Quick way to test if all dictionary items are 'True'
- Keep only sublist in list if the 2nd elements are repeating
- Is it practical to have both Python 2.7 and 3.3 installed at the same time?
- Does x = None or object() equals to explicit check?
- datetime.now().strftime will not update inside while loop
- Error while copy pasting ranges across sheets xlwings
- Is there a cross-platform signal SIGALRM like threading or asyncio
- match a representation of a number with regex
- Writing Cocoa applications in Python 3
- Python 3.x - Output time taken to execute an operation as DD:HH:MM:SS.SSS
- Cutting board algo
- Convert string of base64 back to base64 bytes
- Completely disable py.test stdin/stdout capturing, within a test (similar to py.test -s)
- Python MongoDB query to get list of documents where '_id' != id
- beautifulsoup get value of attribute using get_attr method
- SQLite execute statement for variable-length rows
- loop through all methods in a python program
- Use variables outside of function
- PyCharm: Executing the script in the console rather than 'run'
- Hashing a csv file in python with a key
- Removing files issue - Python