๐Ÿ“– Beginning Python Programming /
Module: Files Operation

Code Example: Guests Text File

๐Ÿ“– Beginning Python Programming / Files Operation / Code Example: Guests Text File

Code Example

guests = []

while True:
    value = input("Please input a guest name, or 'q' to quit: ")
    if value == "q":
        break
    if len(value) > 0:
        guests.append(value)

with open("guests.txt", "a") as file_obj:
    file_obj.write("\n".join(guests))
    file_obj.write("\n")

print("List saved to guests.txt.")

What if we let user choose where to save the list?

list_name = input("Please enter a list name: ")

Save to the given list name

with open(f"{list_name}.txt", "a") as file_obj:
    file_obj.write("\n".join(items))
    file_obj.write("\n")

print(f"List saved to {list_name}.txt.")

Divide logic into functions

def ask_for_list_name():
    '''Ask the user for list name to save.'''
    list_name = input("Please enter a list name: ")
    return list_name

def get_list_items_input(list_name):
    '''Ask user to input a collection of list items until type 'q'.'''
    items = []
    while True:
        value = input(f"Please input an item for {list_name}, or 'q' to quit: ")
        if value == "q":
            break
        if len(value) > 0:
            items.append(value)
    return items

def save_list(list_name, items):
    '''Save the given items into list_name.txt.'''
    with open(f"{list_name}.txt", "a") as file_obj:
        file_obj.write("\n".join(items))
        file_obj.write("\n")

# Main Program Flow
list_name = ask_for_list_name()
items = get_list_items_input(list_name)
save_list(list_name, items)
print(f"List saved to {list_name}.txt.")