使用 CSV 套件将新列添加到 CSV 并使用 socket.gethostname() 的结果填充它

Using CSV kit to add a new column to a CSV and to populate it with results from socket.gethostname()

我正在尝试编写一个 python 脚本来解析一个 csv 文件 (results.csv),该文件采用其中列出的主机名查找 eac 主机名的 IP 地址并将此数据附加到新列中的 csv 文件。

我进行了一些搜索,但遇到了一些困难。另外,我必须强调,我是 Python 的新手,这是我正在做的事情,以增加我的知识。

我在 OS X 上使用 python 2.7.x,我的代码如下:

#!/usr/bin/python

import socket
import csvkit

with open('results.csv', 'rb') as infile:
    with open('output.csv', 'wb') as outfile:
        writer = csvkit.writer(outfile)
        for row in csvkit.reader(infile):
            IP = socket.gethostname(row)
            writer.writerow(row+[IP])

当我在 PyCharm 中 运行 时,出现以下错误:

/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/xxxxxx/PycharmProjects/typosquating/IP_lookup.py Traceback (most recent call last): File "/Users/xxxxxx/PycharmProjects/typosquating/IP_lookup.py", line 10, in IP = socket.gethostname(row) TypeError: gethostname() takes no arguments (1 given)

Process finished with exit code 1

任何人都可以阐明我在做什么?我可以用上面相同的方式在另一个脚本上使用 socket.gethostname() 来检查 results.csv 文件的内容并在屏幕上输出每个主机名的相关 IP,但它似乎失败了用法。

感谢您的帮助。

socket.gethostname() 不接受任何争论 你要找的是 socket.gethostbyname(hostname)

您可能想要 RTFM