Python To Search Csv File And Return Relevant Info
I have a csv file with information about some computers on our network. I'd like to be able to type from the command line a quick line to bring me back the relevant items from the
Solution 1:
Instead of testing if your input string is in the line, test if your input string is in any of the columns. The any()
function is ideally suited for that:
if any(search_1 in col for col in line):
To break this down a little: each line in your csv.reader()
iterable is itself a list of columns, you can loop over these. for col in line
does just that. We test if search_1
is present in each column with search_1 in col
, and any()
will execute the loop until it finds a column where search_1 in col
is True
, in which case it stops iterating over the loop and returns True
itself. If no match was found False
is returned instead.
Post a Comment for "Python To Search Csv File And Return Relevant Info"