[英]Convert IP in text file to Hostname
I'm trying to get hostnames using IPs from text file, but I'm unable to read all IPs from text file and the output shows only one IP.我正在尝试使用文本文件中的 IP 获取主机名,但我无法从文本文件中读取所有 IP,并且输出仅显示一个 IP。
Below is my COde,下面是我的代码,
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
Thanks.谢谢。
The problem is in:问题在于:
for line in f.read().strip('\n'):
this iterates over the whole file content ( f.read()
) without the trailing \\n
.这会遍历整个文件内容( f.read()
),而没有尾随\\n
。 Strings are iterables in Python, so essentially you are just iterating over each character of the text file.字符串在 Python 中是可迭代的,因此本质上您只是迭代文本文件的每个字符。
Instead, as file objects are iterable, you can do the iteration line by line and get the relevant FQDN:相反,由于文件对象是可迭代的,您可以逐行进行迭代并获得相关的 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.