Update a File Through Python
This project comes from the Google Cybersecurity Certificate. A fictional organization had a list of allowed IP addresses and a list of IP addresses to be removed. I created an algorithm in Python that automated the process of updating the allow list file to remove certain IP addresses.
Importing the Allow List
I first imported the allow list by assigning the file name as a string to the variable “allow_file”. Next, I used a with statement to open the file and the read method to convert it to a string stored in the variable “ip_addresses”:
allow_file = "allow_list.txt"
with open(allow_file, "r") as file:
ip_addresses = file.read()Converting the String into a List
I was able to extract individual IP addresses from the allow list by converting the string into a list using the split() method:
ip_addresses = ip_addresses.split()Get Hunter Hall’s stories in your inbox
Join Medium for free to get updates from this writer.
Iterating through the Remove List
I used a for loop to iterate through each IP address in the remove list. Inside the loop, I used an if statement to remove the IP address from the allow list if it was in the remove list:
for i in remove_list:
if i in ip_addresses:
ip_addresses.remove(i)Updating the File
Finally, I updated the allow list file with the new list of IP addresses by converting the list back to a string with the join() method so I could pass it as an argument for the write() method:
ip_addresses = "\n".join(ip_addresses)After converting back to a string, I used the with statement again with the write() method:
with open(allow_file, "w") as file:
file.write(ip_addresses)Summary
This Python algorithm removes IP addresses listed in a remove list variable from the allow list file of approved IP addresses. The code opens the file, converts it to a string, and then converts that string to a list stored in the variable ip_addresses. Then the IP addresses in the remove list are iterated through using a for loop and evaluated if the element should be removed if it was also a part of the ip_addresses list. Finally, the list was converted back to a string and written over the contents of the allow list to update it.







