Open In App

Extract IP address from file using Python

Last Updated : 10 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Let us see how to extract IP addresses from a file using Python.
 

Algorithm :  

  • 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 : 
     
r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
  • 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 : 
 

test.txt

 

python3




# importing the module
import re
  
# opening and reading the file 
with open('C:/Users/user/Desktop/New Text Document.txt') as fh:
   fstring = fh.readlines()
  
# declaring the regex pattern for IP addresses
pattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
  
# initializing the list object
lst=[]
  
# extracting the IP addresses
for line in fstring:
   lst.append(pattern.search(line)[0])
  
# displaying the extracted IP addresses
print(lst)


Output :

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 :
 

((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

 

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
  • [01]?[0-9][0-9]?- represents numbers from 0 to 199

The file to be processed is test2.txt : 
 

test2.txt 

 

python3




# importing the module
import re
  
# opening and reading the file
with open('test2.txt') as fh:
  string = fh.readlines()
    
# declaring the regex pattern for IP addresses 
pattern =re.compile('''((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.)
{3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)''')
  
# initializing the list objects
valid =[]
invalid=[]
  
# extracting the IP addresses
for line in string:
    line = line.rstrip()
    result = pattern.search(line)
  
    # valid IP addresses
    if result:
      valid.append(line)
  
    # invalid IP addresses  
    else:
      invalid.append(line)
  
# displaying the IP addresses
print("Valid IPs")
print(valid)
print("Invalid IPs")
print(invalid)


Output :



Previous Article
Next Article

Similar Reads

Python - Extract domain name from Email address
Given a String Email address, extract the domain name. Input : test_str = 'manjeet@geeks.com' Output : geeks.com Explanation : Domain name, geeks.com extracted. Input : test_str = 'manjeet@gfg.com' Output : gfg.com Explanation : Domain name, gfg.com extracted. Method #1 : Using index() + slicing In this, we harness the fact that "@" symbol is separ
4 min read
Extract numbers from a text file and add them using Python
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data file handling in Python is done in two types of files: Text file (.txt extension) Binary file (.bin extension) Here we are operating on the .txt file in Python. Through this program
4 min read
Extract Multiple JSON Objects from one File using Python
Python is extremely useful for working with JSON( JavaScript Object Notation) data, which is a most used format for storing and exchanging information. However, it can become challenging when dealing with multiple JSON objects stored within a single file. In this article, we will see some techniques to easily extract multiple JSON Objects from a fi
3 min read
Extract text from PDF File using Python
All of you must be familiar with what PDFs are. In fact, they are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. We will extract text from pdf files using two Pytho
3 min read
How to extract Time data from an Excel file column using Pandas?
Prerequisite: Regular Expressions in Python In these articles, we will discuss how to extract Time data from an Excel file column using Pandas. Suppose our Excel file looks like below given image then we have to extract the Time from the Excel sheet column and store it into a new Dataframe column. For viewing the Excel file Click Here. Approach: Im
2 min read
How to extract Email column from Excel file and find out the type of mail using Pandas?
In this article, Let's see how to Extract Email column from an Excel file and find out the type of mail using Pandas. Suppose our Excel file looks like below given image, and then we have to store different type of emails in different columns of Dataframe. For viewing the Excel file Click Here Approach: Import required module.Import data from Excel
3 min read
How to extract date from Excel file using Pandas?
Prerequisite: Regular Expressions in Python In this article, Let's see how to extract date from the Excel file. Suppose our Excel file looks like below given image then we have to extract the date from the string and store it into a new Dataframe column. For viewing the Excel file Click Here. Approach : Import required module.Import data from Excel
3 min read
Python program to extract Email-id from URL text file
Prerequisite : Pattern Matching with Python Regex Given the URL text-file, the task is to extract all the email-ids from that text file and print the urllib.request library can be used to handle all the URL related work. Example : Input : Hello This is Geeksforgeeks review-team@geeksforgeeks.org review-team@geeksforgeeks.org GfG is a portal for gee
1 min read
How To Extract Data From Common File Formats in Python?
Sometimes work with some datasets must have mostly worked with .csv(Comma Separated Value) files only. They are really a great starting point in applying Data Science techniques and algorithms. But many of us will land up in Data Science firms or take up real-world projects in Data Science sooner or later. Unfortunately in real-world projects, the
6 min read
How to extract paragraph from a website and save it as a text file?
Perquisites: Beautiful soupUrllib Scraping is an essential technique which helps us to retrieve useful data from a URL or a html file that can be used in another manner. The given article shows how to extract paragraph from a URL and save it as a text file. Modules Needed bs4: Beautiful Soup(bs4) is a Python library used for getting data from HTML
2 min read
three90RightbarBannerImg