python - python 从txt文件ping ip地址
问题描述
trhe 代码从 txt 中获取 IP 地址。当服务器在线时写入新的txt文件。但是这段代码只写了txt文件中的最后一个文件。而且永远不会有时间进入else。我需要帮助
坦克
import os
file = open("IPs.txt","r+")
with open("IPs.txt","r") as file:
for line in file:
response = os.system("ping " + line)
if response == 0:
with open("IPsCheck.txt","w") as file:
print(line)
file.write(line)
else:
print("server not available ")
解决方案
您需要以附加模式打开输出文件(IPsCheck.txt):“a+”
有关更多信息,请参见此处https://www.guru99.com/reading-and-writing-files-in-python.html#2
下面的代码似乎工作。如果要从 ips 文件中读取 ips,请将 DEBUG 更改为 False。
import os
DEBUG = True
DEBUG_IPS = ['1.1.1.1', '8.8.8.8']
if DEBUG:
ips = DEBUG_IPS
else:
with open("IPs.txt", "r+") as ips_file:
ips = [ip.strip() for ip in ips_file.readlines()]
with open("IPsCheck.txt", "w") as available_ips_file:
for ip in ips:
response = os.system('ping {}'.format(ip))
if response == 0:
available_ips_file.write(ip)
else:
print('server {} not available'.format(ip))
推荐阅读
- ios - Bolt-Swift:错误处理
- excel - Excel 数据透视表 - 组间隔不均匀
- javascript - d3 分组图表第一级不循环
- php - 使用 PHP 循环遍历多维数组
- swift - 只有在当前循环中收到异步回调后,有没有办法在 for 循环中继续进行下一次迭代?
- mysql - 具有主键的同一查询的两个实例上的 MySQL InnoDB 死锁
- android - Unity:DllNotFoundException(Unity 2018.2;Android)
- android - 这是我的 android 代码吗?我想在 textview 中显示值 toast vale
- python - 通过循环另一列来创建新列...不工作
- python - 使用python转换空格分隔的文本文件?