【问题标题】:Python to search CSV file and return relevant infoPython 搜索 CSV 文件并返回相关信息
【发布时间】:2023-11-13 00:17:02
【问题描述】:

我有一个 csv 文件,其中包含有关我们网络上某些计算机的信息。我希望能够从命令行键入一个快速行,以从 csv 中带回相关项目。格式:

$ tag.py *hostname*

csv 有大约 50 列,其中包含从 MAC 地址到上次在网络上看到的信息。我只想在搜索时输出这些列的选择。我已经编写了必要的代码并且它可以工作。但是我希望搜索更加灵活。就目前而言,搜索词需要与我正在搜索的值完全相同。又名

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

如果我搜索主机名或将额外的 0 字符添加到资产编号,我希望代码能够忽略 fqdn。我想我可以通过 len(search_1) &lt; 8 在前面附加一些 0 来解决资产编号问题,直到它有 8 个字符长,但这避免了我真的更愿意只搜索字符串而不对其进行操作以匹配我正在寻找的东西。

【问题讨论】:

    标签: python regex csv python-3.x


    【解决方案1】:

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

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

    稍微分解一下:csv.reader() iterable 中的每一行本身就是一个列列表,您可以遍历这些列。 for col in line 就是这样做的。我们测试search_1 是否存在于带有search_1 in col 的每一列中,any() 将执行循环,直到找到search_1 in colTrue 的列,在这种情况下,它停止迭代循环并返回@ 987654331@ 本身。如果未找到匹配项,则返回 False

    【讨论】:

    • 非常感谢。这正是我所需要的。它现在完美运行:)