Let us see how to extract IP addresses from a file using Python.
- Import the
remodule for regular expression.
- Open the file using the
- Read all the lines in the file and store them in a list.
- Declare the patter for IP addresses. The regex pattern is :
- For every element of the list search for the patter 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 :
- Python - Extract domain name from Email address
- Extract numbers from a text file and add them using Python
- Extract text from PDF File using Python
- How to extract Time data from an Excel file column using Pandas?
- How to extract Email column from Excel file and find out the type of mail using Pandas?
- How to extract date from Excel file using Pandas?
- Python program to extract Email-id from URL text file
- reStructuredText | .rst file to HTML file using Python for Documentations
- Create a GUI to convert CSV file into excel file using Python
- Extracting MAC address using Python
- Python program to determine if the given IPv4 Address is reserved using ipaddress module
- Python program to determine if the given IP Address is Public or Private using ipaddress module
- Python | Program to extract frames using OpenCV
- Python | Draw rectangular shape and extract objects using OpenCV
- Python | Extract URL from HTML using lxml
- Extract dominant colors of an image using Python
- PYGLET – Opening file using File Location
- Python program to reverse the content of a file and store it in another file
- Python - Get file id of windows file
- Address Calculation Sort using Hashing
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.