Reputation: 1
Very new to python and self teaching at the moment, so apologies if the example is wrong/basic. Feel free to improve it :)
Basically the file MEs.txt contains a list of IP addresses, once it pings the ip address and gets a response I was trying to get the printout of 'ME (line number) is connected/disconnected).
Any help?
os.remove("EquipmentCheck.txt")
file = open("MEs.txt", "r+")
with open("MEs.txt", "r") as file:
for line in file:
response = os.system("ping " + line)
if response == 0:
with open("EquipmentCheck.txt", "a") as file:
file.write("ME is connected" "\n")
else:
with open("EquipmentCheck.txt", "a") as file:
file.write("ME is disconnected" "\n")```
Upvotes: 0
Views: 123
Reputation: 1835
try with enumerate()
enumerate(iterable, start=0)
Parameters:
Iterable: any object that supports iteration
Start: the index value from which the counter is to be started, by default it is 0
with open("MEs.txt") as fp:
for i, line in enumerate(fp):
print("%d, %s"%(i, line))
Upvotes: 0
Reputation: 13731
One option is to use the enumerate
function.
for index, line in enumerate(file):
line_number = index + 1
...
Apparently there's a start parameter. So you could do:
for line_number, line in enumerate(file, start=1):
...
Upvotes: 4