user4414636
user4414636

Reputation:

Unable to compare strings with lines in file

I'm trying to check if a certain key exists in a file:

Here's how I'm storing keys into the file:

def cache_key(key):
    with open(file_name, "a") as processed:
            processed.write(key + "\n")

Here's how I'm comparing:

def check_key_exists(key):
    cache_file = open(file_name)
    for line in cache_file:
        if(str(line) == str(key)):
            cache_file.close()
            return True
    cache_file.close()
    return False


def some_func():
    for submission in subs.get_new(limit=75):
        if check_key_exists(submission.id):
            break
        else:
            do_something()

But even if the key exists within the file, check_key_exists() always returns False. What am I doing wrong?

Upvotes: 0

Views: 53

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

Your file has a newline character after each keyword (of course!), which I suppose is not part of your key parameter.

You could do

def check_key_exists(key):
    with open(file_name) as cache_file:
        for line in cache_file:
            if line.strip() == key:
                return True
    return False

Note that you don't need str() - your parameters should already be strings.

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

Since you are adding a new line character at the end of your lines, you need to strip the lines, when you want to compare them with keys:

if (line.strip() == str(key)) :

Also note that if the key is a string you don't need to convert it to string by calling the str() function.

Upvotes: 2

Related Questions