gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
Write Python script to parse all IP addresses from file to list
- User
Write Python script to parse all IP addresses from file to list
- 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
remodule (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:
- Imports: The script imports the
remodule which provides support for regular expressions. - Function Definition: The function
extract_ips_from_filetakes 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\bis 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.
- 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.
- Imports: The script imports the