Python to search CSV file and return relevant info

2024/11/15 23:58:03

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 csv. In the format:

$ tag.py *hostname*

The csv has about 50 columns with information ranging from MAC address to last time seen on the network. I only want to output a selection of these columns when I search. I've written the necessary code and it works. However I want the search to be more flexible. As it stands, the search term needs to be exactly the same as the value I'm searching for. aka

$ tag.py mycomputer        # This returns nothing
$ tag.py mycomputer.co.uk  # This returns the information I want
$ tag.py 63746             # This returns nothing
$ tag.py 00063746          # This returns the information I want

So now for the code I have.

# Import Modulesimport sys
import csv# Get user Input
# I assume the script is used in the form script.py "search-term"
# If no input added to command, ask for user inputif len(sys.argv) < 2:print("Please enter a hostname or asset number.")search_1 = input("Search for:")
else:search_1=sys.argv[1]# Setup Variables
# Open cvs and setup csv.reader settingscsvfile = open("file.csv", "r", encoding="Latin-1")
csvfile.seek 
reader = csv.reader(csvfile, dialect='excel', delimiter=",", quotechar="'")# Search cvs for the input stringfor line in reader:if search_1 in line:print("------------------------------------------------------")print("  Hostname = " + line[10])print("  " + line[11])print("  AssetId = " + line[30])print("  IP = " + line[7])print("  MAC = " + line[6])print("  Owner = " + line[15])print("  Username = " +line[14])print("  Tel = " + line[17])print("  Last Seen = " + line[27])print("------------------------------------------------------")csvfile.close()

I would like the code to be able to ignore the fqdn if I search for a hostname or to add the extra 0 characters to the asset number. I think I can fix the asset number issue with a len(search_1) < 8 append some 0 to the front until it is 8 characters long but that's avoiding the fact that I really would prefer to just search for the string without manipulating it to match the thing I'm looking for.

Answer

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.

https://en.xdnf.cn/q/118994.html

Related Q&A

Remove all elements matching a predicate from a list in-place

How can I remove all elements matching a predicate from a list IN-PLACE? T = TypeVar("T")def remove_if(a: list[T], predicate: Callable[[T], bool]):# TODO: Fill this in.# Test: a = [1, 2, 3, …

Python-scriptlines required to make upload-files from JSON-Call

Lacking experience & routine for Python-programming. Borrowing examples from forums have made a script which successfully makes a JSON-cal (to Domoticz) and generates & prints the derived JSON-…

python pygame mask collision [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 4 years ago.The com…

How to find max average of values by converting list of tuples to dictionary?

I want to take average for all players with same name. I wrote following code. its showing index error whats the issue?Input: l = [(Kohli, 73), (Ashwin, 33), (Kohli, 7), (Pujara, 122),(Ashwin, 90)]Out…

Cannot pass returned values from function to another function in python

My goal is to have a small program which checks if a customer is approved for a bank loan. It requires the customer to earn > 30k per year and to have atleast 2 years of experience on his/her curren…

What is the difference here that prevents this from working?

Im reading a list of customer names and using each to find an element. Before reading the list, I make can confirm this works when I hard-code the name,datarow = driver.find_element_by_xpath("//sp…

How can I extract numbers based on context of the sentence in python?

I tried using regular expressions but it doesnt do it with any context Examples:: "250 kg Oranges for Sale" "I want to sell 100kg of Onions at 100 per kg"

Chart with secondary y-axis and x-axis as dates

Im trying to create a chart in openpyxl with a secondary y-axis and an DateAxis for the x-values.For this MWE, Ive adapted the secondary axis example with the DateAxis example.from datetime import date…

Env var is defined on docker but returns None

I am working on a docker image I created using firesh/nginx-lua (The Linux distribution is Alpine): FROM firesh/nginx-luaCOPY ./nginx.conf /etc/nginx COPY ./handler.lua /etc/nginx/ COPY ./env_var_echo.…

No Browser is Open issue is coming when running the Robot framework script

I have created Test.py file which has some function in it and using those function names as Keywords in sample.robot file. Ex: - Test.pydef Launch_URL(url):driver.get(url)def article(publication): do…