File Handling in Python

Python provides comprehensive functionality for file operations, allowing developers to read, write, and manipulate files efficiently. Below is a detailed overview of file functions and methods in Python.

File Opening and Closing

  • open() - Opens a file and returns a file object
  • close() - Closes an open file
  • with statement - Context manager that automatically closes files

File Opening Modes

  • 'r' - Read mode (default)
  • 'w' - Write mode (creates new file or truncates existing file)
  • 'a' - Append mode (adds to end of file)
  • 'x' - Exclusive creation mode (fails if file exists)
  • 'b' - Binary mode
  • 't' - Text mode (default)
  • '+' - Update mode (read and write)

Reading from Files

  • read() - Reads entire file content or specified number of bytes
  • readline() - Reads a single line from a file
  • readlines() - Reads all lines into a list
  • seek() - Changes file position to specified offset
  • tell() - Returns current file position
  • truncate() - Resizes file to specified size

Writing to Files

  • write() - Writes string to file
  • writelines() - Writes list of strings to file

File Properties and Information

  • name - Returns name of the file
  • mode - Returns the mode in which file was opened
  • closed - Returns True if file is closed
  • encoding - Returns file encoding

File System Operations

  • os.remove() - Deletes a file
  • os.rename() - Renames a file
  • os.path.exists() - Checks if a file exists
  • os.path.getsize() - Returns file size in bytes
  • os.path.isfile() - Checks if path is a file
  • os.path.isdir() - Checks if path is a directory
  • os.makedirs() - Creates directories recursively
  • os.listdir() - Lists files and directories in a path
  • os.path.join() - Joins path components intelligently

Advanced File Operations

  • fileinput - Iterates over lines from multiple input files
  • tempfile - Creates temporary files and directories
  • shutil - Provides high-level file operations (copy, move, etc.)
  • pathlib - Object-oriented filesystem paths

File-like Objects

  • StringIO/BytesIO - In-memory file-like objects for text/binary data
  • file iterators - Iterating over file objects line by line

Binary File Operations

  • read()/write() - Reads/writes bytes in binary mode
  • struct - Interprets bytes as packed binary data

File Encoding and Decoding

  • encoding parameter - Specifies text encoding when opening files
  • errors parameter - Controls error handling for encoding/decoding issues

Python's file handling functions provide a robust foundation for working with files of all types. From basic text processing to complex binary manipulations, these functions enable efficient file operations across various use cases. Understanding these file functions is essential for developing applications that need to interact with the file system or process data from external sources.