调用dnspython,将csv文件中的第二列(域名),转为ip并且保存到第四列,csv以utf-8编码,
时间: 2024-10-11 08:16:00 浏览: 21
要在Python中使用`dnspython`库将CSV文件中的域名转换成IP地址,并将其添加到新的第四列,你需要首先安装`dnspython`。如果你还没安装,可以使用pip来安装:
```bash
pip install dnspython
```
接下来是一个示例脚本,它会读取CSV文件,查询域名并添加新列:
```python
import csv
from dns.resolver import Resolver
def resolve_domain_to_ip(domain):
resolver = Resolver()
try:
answer = resolver.resolve(domain, 'A')
return str(answer[0].address)
except Exception as e:
# 如果解析失败,可以在这里处理异常,例如记录日志或返回默认值
print(f"Failed to resolve {domain}: {e}")
return None
def process_csv(input_file, output_file):
with open(input_file, encoding='utf-8') as csvfile, \
open(output_file, 'w', newline='', encoding='utf-8') as newfile:
reader = csv.reader(csvfile)
writer = csv.writer(newfile)
header = next(reader) # 获取原始表头
header.insert(3, "IP Address") # 添加新的第四列
writer.writerow(header)
for row in reader:
domain = row[1] # 第二列
ip = resolve_domain_to_ip(domain)
if ip:
row.append(ip) # 添加新列
writer.writerow(row)
# 使用函数处理CSV文件
process_csv('input.csv', 'output.csv')
```
在这个例子中,`process_csv`函数会遍历输入文件的每一行,把第二列的域名传给`resolve_domain_to_ip`函数,然后将结果添加到新的一列中。
阅读全文