Python Classroom Session – 28/Sept/2020

File Handling in Python

  • In our ltrestaurant, we have built a simple menu class, this can handle adding, updating items.

  • The problem is when we restart application we need to the whole menu again, As we are using menu to add items in memory (RAM), So we need to modify this menu class to store the data of the menu on to the file system

  • File Input & Output:

    • Lets Create a simple version of the file flat files
    • Create or Open the file with open()
    file_object = open( file, mode)
    • The first letter of mode indicates operation
      • r => read
      • w => write, If the file doesnt exist file is created. If the file exists contents are overriten
      • x => write, only if the file does not exist
      • a => append
    • The second letter of mode indicates file’s type
      • t => text
      • b => binary
    • Lets create a simple text file with content Im storing text using print method Refer Here for the code
    • Write a text file using write() Refer Here
    • Lets try to create menuitems.csv
    • While dealing with files we need to perform read operations also
      • python provide text file reads with read(), readline() and readlines()
      • Refer Here for usage examples
  • Next Steps:

    • How to deal binary files
    • How to store custom objects like menu_items into files


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin