gpt4 book ai didi

python - 将文本文件中的 IP 转换为主机名

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:45 25 4
gpt4 key购买 nike

我正在尝试使用文本文件中的 IP 获取主机名,但我无法从文本文件中读取所有 IP,并且输出仅显示一个 IP。

下面是我的代码,

import os
import socket

with open('ips.txt', 'r') as f:
for line in f.read().strip('\n'):
ip = line.strip()
b = socket.getfqdn(ip)
print b

谢谢。

最佳答案

问题出在:

for line in f.read().strip('\n'):

这会迭代整个文件内容 (f.read()),不带尾随 \n。字符串在 Python 中是可迭代的,因此本质上您只是迭代文本文件的每个字符。

相反,由于文件对象是可迭代的,您可以逐行进行迭代并获取相关的 FQDN:

with open('ips.txt', 'r') as f:
for line in f:
ip = line.strip()
fqdn = socket.getfqdn(ip)
# print(fqdn) # Python 3
print fqdn # python 2

关于python - 将文本文件中的 IP 转换为主机名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48834100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com