Skip to main content

1. What is File Handling?

  • File handling refers to reading from and writing to files in Python.
  • Files are used to store data persistently, even after the program ends.
  • Python provides built-in functions and methods to work with files.

2. Opening a File

  • Use the open() function to open a file.
  • Syntax: open(filename, mode)
  • Modes:
    • "r" : Read mode (default). Opens the file for reading.
    • "w" : Write mode. Opens the file for writing (creates a new file or overwrites an existing file).
    • "a" : Append mode. Opens the file for appending (writes data to the end of the file).
    • "x" : Exclusive creation mode. Creates a new file but raises an error if the file already exists.
    • "b" : Binary mode (e.g., "rb", "wb").
    • "+" : Read and write mode (e.g., "r+", "w+").
Example:

3. Closing a File

  • Always close a file after working with it using the close() method.
  • This releases system resources and ensures data is properly saved.
Example:

4. Using with Statement

  • The with statement automatically closes the file after the block of code is executed.
  • It is the recommended way to work with files.
Example:

5. Reading from a File

1. read()

  • Reads the entire content of the file as a string.
Example:

2. readline()

  • Reads a single line from the file.
Example:

3. readlines()

  • Reads all lines from the file and returns them as a list.
Example:

6. Writing to a File

1. write()

  • Writes a string to the file.
Example:

2. writelines()

  • Writes a list of strings to the file.
Example:

7. Appending to a File

  • Use the "a" mode to append data to the end of a file.
Example:

8. Working with Binary Files

  • Use the "b" mode to read or write binary data (e.g., images, videos).
Example:

9. File Methods and Attributes

1. seek()

  • Moves the file pointer to a specific position.
Example:

2. tell()

  • Returns the current position of the file pointer.
Example:

3. truncate()

  • Resizes the file to a specified size (in bytes).
Example:

10. Additional Examples

1. Reading a File

2. Writing to a File

3. Appending to a File

4. Reading and Writing Binary Data

11. Best Practices

  • Always use the with statement to ensure files are properly closed.
  • Handle exceptions (e.g., FileNotFoundError) when working with files.
  • Use meaningful file names and organize files in directories.
  • Avoid hardcoding file paths; use relative paths or configuration files.
Example: