How do i read from a file in python?



  • Also see: https://www.lightnetics.com/post/9894

    Similar to writing to a file we can read from a file.

    The functions used here are read function and the readline function.

    Use readline function to print out line of the file at a time.

    cake_shopping_file = open("cakestobuy.txt", "r")
    
    print(cake_shopping_file.readline())
    print(cake_shopping_file.readline())
    print(cake_shopping_file.readline())
    cake_shopping_file.close()
    

    Result is:
    fruit

    ginger

    lemon

    Read the entire file.

    cake_shopping_file = open("cakestobuy.txt", "r")
    
    print(cake_shopping_file.read())
    cake_shopping_file.close()
    

    Result is:
    fruit
    ginger
    lemon


Log in to reply
 

© Lightnetics 2024