z.yea
z.yea

Reputation: 73

Appending similar strings to a file

Hi I am running into a small issue when appending a string into a file. So basically, I am appending books that does not exist in the file using this:

def writeBooks2File(booklist_dir):
    BOOKS = ['Human Philosophy', 'Human Philosophy book']
    for val in BOOKS:
        if val not in open(booklist_dir, "r").read():
            f = open(booklist_dir, "a")
            f.write(val + "\n")
            f.close()

My file contains the following:

Human Philosophy
Human Philosophy book

Lets say I remove Human Philosophy, the file contains Human Philosophy book only. Running writeBooks2File(booklist_dir) again does not return this output:

Human Philosophy
Human Philosophy book

But return this instead:

Human Philosophy book

What do I need to do to make add Human Philosophy into the file with both values being similar to one another.

Upvotes: 0

Views: 35

Answers (1)

Martin
Martin

Reputation: 3385

The problem is that

>>> 'Human Philosophy' in 'Human Philosophy book\n'
True

Therefore you can do this:

>>> ('Human Philosophy'+'\n') in 'Human Philosophy book\n'
False

I rewrote your script... This should give you better using

def writeBooks2File(booklist_dir,books):
    f = open(booklist_dir, "a")
    for val in books:
        if val+'\n' not in open(booklist_dir, "r").read():

            f.write(val + "\n")
    f.close()

def removebooks(booklist_dir,books):
    with open(booklist_dir, "r") as File:
        all_books = File.read()
    for book in books:
        new = all_books.replace(book+'\n','')
    with open(booklist_dir, "w") as File:
        File.write(new)
books = ['Human Philosophy book','Human Philosophy']        
writeBooks2File('test.txt',books)

remove_books = ['Human Philosophy'] 
removebooks('test.txt',remove_books)

With this, you can do what you were not able to do. Append the file with 'Human Philosophy' even if there is 'Human Philosophy book'

Upvotes: 1

Related Questions