Extract IP address from file using Python
Let us see how to extract IP addresses from a file using Python.
- Import the re module for regular expression.
- Open the file using the open() function.
- Read all the lines in the file and store them in a list.
- Declare the pattern for IP addresses. The regex pattern is :
- For every element of the list search for the pattern using the search() function, store the IP addresses in a list.
- Display the list containing the IP addresses.
The file to be processed is test.txt :
The above Python program displays any kind of IP addresses present in the file. We can also display the valid IP addresses.
Rules for a valid IP Address :
- The numbers should be in a range of 0-255
- It should consist of 4 cells separated by ‘.’
The regular expression for valid IP addresses is :
Explanation of Regular Expression used for valid IP:
Since we cannot use 0-255 range in regular expression we divide the same in 3 groups:
- 25[0-5] – represents numbers from 250 to 255
- 2[0-4][0-9] – represents numbers from 200 to 249
- ?[0-9][0-9]?- represents numbers from 0 to 199
The file to be processed is test2.txt :