Update a file and check if a string is already in it with Python

Another small installment of my Web-Scraping series.

f = open('list.txt', 'a+', encoding='utf-8')
f.seek(0)

fr = f.read().splitlines()
if name not in fr:
    f.write(name + '\n')
f.close()

I use a+ so that if the file does not exist, the code creates it. I order to properly read the content I need to point to the first symbol with f.seek(0). I could use r+ so that I would start with thr first symbol automatically, but it would not create the file if it did’nt exist.

With just f.readlines() I would get a list with names and newlines \n, so to get just names, I use f.read().splitlines().

Whether I write to the file or not, I need to close it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.