momo
momo

Reputation: 2763

Get file content and make a list

I am a newbie trying to get the content in a file and make a list from it.

I want to print "There is no item." when the file is empty, and "You have xxx."(xxx being the item name) when there is only one string in the file (e.g. 'banana').

Content of my_file.txt:
banana,mango,peach,apple


with open("my_file.txt", "r+") as f:
    items = f.read()
    items = items.replace('\n', '').replace(' ', '')
    items = items.split(",")
    last_item = items[-1]
    items_ex_last_item = items[:-1]
    print("You have " + ', '.join(items_ex_last_item) + " and " + last_item + ".")

Upvotes: 0

Views: 76

Answers (3)

user
user

Reputation: 5696

The list comprehension filters out empty strings. Then if checks if the remaining list is empty. If not empty, checks length and prints accordingly.

with open("my_text_file.txt", "r") as f:
    items = f.read()
    items = items.replace('\n', '').replace(' ', '')
    items = items.split(",")

    items = [i for i in items if i]
    if items:

        if len(items) == 1:
            print('You have {}'.format(items[0]))

        if len(items) > 1:
            last_item = items[-1]
            items_ex_last_item = items[:-1]
            print("You have " + ', '.join(items_ex_last_item) + " and " + last_item + ".")

    else:
        print("There is no item.")

items = [i for i in items if i] is the equivalent of the following code:

new_lst = []
for i in items:
    if i:
        new_lst.append(i)
items = new_lst

Loops through all elements in items list, and checks if i is True. If it is, then it will append() it into the list. Finally, it makes items refer to the new_lst, effectively replacing items' old contents.

How if x: works (link):

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142136

You can use next which will raise a StopIteration which in this case will signify the file is empty, and use tuple unpacking to get items until the last, and the last item, then decide what to print based on that, eg:

with open('my_file.txt') as fin:
    try:
        *items, last = next(fin).split(',')
        if not items: print('You have', last)
        else: print('You have', ', '.join(items) + ' and ' + last)
    except StopIteration:
        print('No items')

Upvotes: 1

ferhatelmas
ferhatelmas

Reputation: 3978

from collections import Counter
from operator import itemgetter

with open('my_file.txt', 'rb') as f:
    res = '\n'.join(
        'You have {} ({})'.format(v, k)
        for k, v in sorted(
            Counter(f.read().strip().split(',')),
            key=itemgetter(1, 0), reverse=True)
    )
    print res if res else 'There is no item'

Upvotes: 0

Related Questions