def opening_files(words): file = open("words.txt") judge=False for line in file: if words == line: judge = True break return judge Hi! Fellow OCW students! Using a code above, I'm trying to return True if there's a match inside of my text file, but even if I put a word that is in the file, it keeps returning False. Can anybody spot a error on my code? Thanks!!!
I'm assuming your "words == line" returns false, meaning words does NOT or "!=" line.
I'm not positive, but usually when you open a text file like that it is in the form of a string of characters, so "for line in file" is perhaps treating each "line" as a character (hence no character is being checked as a word). If you have a text file and you want to get the words into some kind of list you could use the .split() method (look it up in the python standard library if you don't know it).
use line.strip() - it is reading line + '\n', if words == line.strip() : # this works for me...
oh I think that's what I meant :P
oh no, they are different, ic
Thank you so much for your help guys! line.strip() # this works, but I don't know why this works though. This is the definition of stip(), but I don't understand how strip works in my code. Strip([char]): Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
I have one more question. I want my code to recognize both lowercase and uppercase. How can I do that?
you can use the lower() function to turn them all to lower case first. :)
AttributeError: 'file' object has no attribute 'lower' # I have an errors message when using lower() Also, I want it to recognize both lowercase and uppercase, not just lowercase. Is that possible?
lower() is a method of the string object, not the file object, so "FOO".tolower() is "foo". If you're doing string comparisons, they are done case sensitively. As far as the computer is concerned, strings are just a series of one or two byte (depending on the character encoding) integers.
Join our real-time social learning platform and learn together with your friends!