Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-05-13· OpenAIAi2 WildChat-4.8M (AI2)

Write Python script to parse all IP addresses from file to list

  1. User

    Write Python script to parse all IP addresses from file to list

  2. Assistant

    Certainly! Below is an example of a Python script that reads a file, extracts all IP addresses, and stores them in a list. This script uses the re module (regular expressions) to find IP addresses in the file:

    import re
    
    def extract_ips_from_file(filename):
        with open(filename, 'r') as file:
            content = file.read()
        
        # Regular expression for matching IP addresses
        ip_pattern = re.compile(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b')
        
        # Find all IP addresses in the file content
        ip_addresses = ip_pattern.findall(content)
        
        return ip_addresses
    
    # Example usage
    if __name__ == "__main__":
        file_path = 'your_file.txt'  # Replace with your file path
        ip_list = extract_ips_from_file(file_path)
        print(ip_list)
    

    Explanation:

    1. Imports: The script imports the re module which provides support for regular expressions.
    2. Function Definition: The function extract_ips_from_file takes a filename as an argument.
      • It opens the file and reads its content.
      • It compiles a regular expression pattern to match IP addresses (\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b), where \b is a word boundary and (?:[0-9]{1,3}\.){3}[0-9]{1,3} matches a sequence of four groups of 1 to 3 digits, separated by dots.
      • It then finds all the matches of this pattern in the file content and returns them as a list.
    3. Example Usage: The file path is specified, and the function is called to extract the IP addresses from the file. The resulting list of IP addresses is printed.

    Replace 'your_file.txt' with the path to your specific file containing the IP addresses you'd like to extract.

    Make sure your input file is formatted in a way that contains IP addresses as per the regex pattern defined. The pattern provided will match typical ipv4 addresses. If you need to match ipv6 addresses or have more complex requirements, you may need to adjust the regex pattern accordingly.