简体   繁体   中英

reading from a file and checking if word in list

my wife texts me unorganized and long grocery lists. I will paste her list into a text file. I want to write a program that will will erase her unordered list and write to that file an ordered list. ex all fruit together, meat together ect. clearly this program is in its infancy. in my text file, I have written:

banana
apple

in this case, when I iterate through each line of my text file, I expect item to be appended to fruit? but it is not. what have I missed?

fruit = []
vegetables = []
meat = []
dairy = []
fruit_list = ["banana", "apple", "orange"]

def read_list():
    with open("/storage/emulated/0/textfiles/grocery.txt", "r") as r:
        for item in r:
            if item in fruit_list:
                fruit.append(item)
    print(fruit)

You need to strip the line endings from the file, as they are carrying \\n or \\r\\n (Windows carriage return) at the ends. This means you are comparing banana with banana\\n , which are not equal, leading to nothing being appended.

You can fix this by using str.strip() beforehand like so:

item = item.strip()
if item in fruit_list:
    # rest of code

Or you can just strip from the right with str.rstrip() :

item = item.rstrip()
if item in fruit_list:
    # rest of code

You could also strip everything while iterating with map() :

for item in map(str.strip, r):
    # rest of code

But the first two solutions are fine.

Use .rstrip() to cut '\\n' simbols from end of lines

def read_list():
    with open("grocery.txt", "r") as r:
        for item in r:
            if item.rstrip() in fruit_list:
                fruit.append(item)
    print(fruit)

read_list()

also you can use item.rstrip().lower() to check items that starts with Upper letter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM