Reputation: 323
i am having a problem. I have a blacklist.txt file that contains 5 links
Link1.com
Link2.com
Link3.com
Weirdlink4.com
Fivelink5.com
I also have a Links.txt which contains all these 5 links and 40 more. I am trying to make a script that can read what blacklist.txt contains and remove those links from Links.txt and removing the links aswell in blacklist.txt.
with open("Blacklist.txt", "w+") as blacklist:
with open("Links.txt", "w+") as links:
blackinfo = blacklist.read()
linksinfo = links.read()
for i in blackinfo:
if i in linksinfo:
At this point i am completely confused as to how i am going to delete the link from both files because i is holding the value. Thanks in advance
Upvotes: 0
Views: 59
Reputation: 20561
Using list comprehensions you can create a new list of links that you override your link files with:
with open("Blacklist.txt", "r+") as blacklist_file :
with open("Links.txt", "r+") as links_file :
bl_links = blacklist_file.read().splitlines()
blacklist_file.seek(0) #reset file handle's position to start of file for writing
links = links_file.read().splitlines()
links_file.seek(0)
# Only keep blacklist links that did not exist in links
new_blacklist_links = [link for link in bl_links if link not in links]
# Only keep links that did not exist in the blacklist
new_links = [link for link in links if link not in bl_links]
blacklist_file.write('\n'.join(new_blacklist_links))
blacklist_file.truncate() #truncate the file to what we have just written
links_file.write('\n'.join(new_links))
links_file.truncate()
Upvotes: 2