File Handling - Python

  • OS Module
    • import os => Import module
    • os.mkdir("folderPath") => Creates a folder in the current directory
      • If folder already exists then gives error
    • varName = open("filePath", os.O_RDONLY) => Open file in read only mode
    • varName = open("filePath", os.O_WRONLY) => Open file in write only mode
    • varName1 = os.read(varName, 1024) => Read contents of the file
    • os.close() => Close the file
    • os.path.exists("filePath") => Returns true of file/folder exists
    • os.rename("sourceFilePath", "destinationFilePath") => Renames
    • os.listdir("folderPath") => Returns list of folders
    • os.getcwd()
    • os.system("date")
  • Shutil Module
  • File handling
    • varName = open("fileName", "r") => Open file in reading mode, Gives error if file does not exist
      • varName = open("fileName") => Default mode is reading
      • varName1 = varName.read() => Gets content of the file
    • varName = open("fileName", "w") => Open file in writing mode, Creates a new file if it does not exist
      • varName.write("value") => Write in file, Needs to close the file
    • varName = open("fileName", "a") => Appending in file, Creates a new file if it does not exist
      • varName.write("value") => Appends in file
    • varName = open("fileName", "x") => Creates file, Gives error if it already exist
    • varName = open("fileName", "rt") => Used to handle text file, Default is this mode
      • varName = open("fileName", "wt")
    • varName = open("fileName", "rb") => Used to handle binary files, Images, PDFs
    • varName.close() => Closes the opened file
    • No need to close manually
          with open("fileName", "w") as f:
              f.write("value")
              f.truncate(N) # Truncates the file to specified size
      
    • Seek => Allows you to move the current position within the file to a specific point, Position is specified in bytes
          with open("fileName", "r") as f:
              f.seek(N) # Move to Nth byte in file
              varName = f.read(N) # Read the next N bytes
              f.tell() # Returns the current position within the file in bytes
      
Share: