Python Essentials Classroom Series- 12/Aug/2021

Files in Python

  • While databases such as MySQL and Postgres are popular and widely used in many web applications, there is still a large amount to data that is stored and exchanged sing text file formats.

  • Popular formats are

    • Comma Seperated Values,
    • Java Script Object Notation (JSON)
    • YAML
    • Plain text
    • Binary
  • Reading a Text file using python

    • Refer Here for the sample to read the whole contents of the file
  • Read Partial content from a text file

  • With Statement for opening the files: In python we can use with block to open the files, The advantage of using this approach is as soon as the block is executed, file will be closed automatically.

    • Refer Here for the changeset containing with statements
  • Writing files:

    • In python we use open function to open the file and while opening the file we can specify the mode.
    • Python has following file opening modes
      • r: This is default mode and it opens file for reading
      • w: The Write mode. This opens a file for writing, creates a new file if the file doesnot exist and overrites the contents if the file already exists
      • x: This creates a new file. This operation fails if the file exists
      • a: This opens file in append mode and creates the new file if a file does not exist
      • b: This opens a file in binary mode
    • Lets try to write a program which asks the user to enter the name, course etc and stores the data in a text file. Refer Here
    • Enhance this code by doing the following
    1. Add new enquiry information
    2. Print all the data
    3. quit
    Enter your choice? (1 or 2) 
    

Leave a Comment

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

About continuous learner

devops & cloud enthusiastic learner