2013-03-11 75 views
-1

我有一个csv文件,其中包含有关我们网络中某些计算机的信息。我希望能够通过命令行输入一行快捷方式,将csv中的相关项目带回。的格式为:Python来搜索CSV文件并返回相关信息

$ tag.py *hostname* 

该CSV具有信息,从MAC地址在网络上看到最后一次约50列。我只想在搜索时输出这些列的选择。我已经编写了必要的代码并且工作正常。不过,我希望搜索更灵活。就目前而言,搜索字词必须与我正在搜索的值完全相同。又名

$ 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 

所以现在的代码我有。

# Import Modules 

import 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 input 

if 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 settings 

csvfile = open("file.csv", "r", encoding="Latin-1") 
csvfile.seek 
reader = csv.reader(csvfile, dialect='excel', delimiter=",", quotechar="'") 

# Search cvs for the input string 

for 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() 

我想代码可以,如果我搜索了主机忽略FQDN或额外的0字符添加到资产编号。我想我可以通过len(search_1) < 8在前面附加一些0来修正资产编号问题,直到它的长度为8个字符为止,但这样做避免了我真的宁愿只搜索字符串而不操纵它来匹配我寻找。

回答

1

而不是测试您的输入字符串是否在行中,测试您的输入字符串是否在任何列中。该any() function是非常适用于:

if any(search_1 in col for col in line): 

要打破这一点:在你的csv.reader()迭代每一行本身列的列表,你可以通过这些循环。 for col in line就是这么做的。我们测试每个列中是否存在search_1,其中search_1 in colany()将执行循环,直到找到一列,其中search_1 in colTrue,在这种情况下,它会停止迭代循环并返回True本身。如果找不到匹配,则返回False

+0

非常感谢。这正是我需要的。它现在完美的工作:) – 2013-03-11 11:15:51