Python Classroom Series – 27/Jun/2021

Files and Directories

  • File Input and Output
    • The simplest kind of the persistence is plain old file (flat files)
    • We need to know how to read file into memory and write from memory to file.
  • Create or Open with open()
    • We need to call open function to do the following
      • Read an existing file
      • Write to a new file
      • Append to and existing file
      • Overwrite and existing
      fileobj = open(filename, mode)
      
      • The first letter of mode indicates the operation
        • r means read
        • w means write. (If the file doesn’t exist its created, If file exists it will be overwritten)
        • x mean write but only if the file doesnot already exist
        • a means append (Write at the end) if the file exists
      • The second letter of mode indicates the file type
        • t (or nothing) means text file
        • b means binary file
      config_file = open('config.txt', 'r' ) # open('config.txt', 'rt')
      image_file = open('image1.jpeg', 'rb')
      
      • After opening the file we can call functions like read or write and once you are done with file writing or reading you need to call the close
  • Write a Text file using print():
  • Write a Text File with write():
    • Refer Here for the changeset contianing code to write to a file
  • Read a TextFile with read(), readline() or readlines():

File Operations

  • Check existence with exists() Preview
  • Check type with isfile() Preview
  • Link with link() or symlink()
>>> os.link('config/config.txt', 'fconfig')
>>> os.path.islink('fconfig')
>>> os.symlink('config/config.txt','symconfig')
>>> os.path.islink('symconfig')
  • Change Permissions with chmod(), chown()
os.chmod('config.txt', 0o400)
uid=1001
gid=1001
os.chown('config.txt',uid, gid)
  • Deleting file
os.remove('config.txt')

Directory Operations

Preview Preview

Exercise

  • Try to create a python program which asks the user
    • to enter the item code
    • to enter the item name
    • to enter the price of the item
    • to enter the number of items
  • Use csv.DictWriter to write this information to the file.
  • Refer Here for csv module and Refer Here for DictWriter
  • Refer Here for the sample used in the class.

Leave a Comment

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

About learningthoughtsadmin