Python File Handling

File handling is an essential part of programming. It allows you to read from and write to files, which is crucial for tasks like data storage, configuration, and logging.


Opening a File

Python provides the open() function to open files. The open() function takes two parameters: the filename and the mode.

Tutorials dojo strip

Modes

  • "r": Read mode (default). Opens a file for reading.
  • "w": Write mode. Opens a file for writing (creates a new file if it does not exist or truncates the file if it exists).
  • "a": Append mode. Opens a file for appending (creates a new file if it does not exist).
  • "b": Binary mode. Opens a file in binary mode.

Example:




Reading a File

To read the contents of a file, you can use methods like read(), readline(), or readlines().

Reading the Entire File:

Reading Line by Line:




Writing to a File

To write to a file, you can use the write() or writelines() methods. Make sure to open the file in write ("w") or append ("a") mode.

Writing a Single Line:

Writing Multiple Lines:




Appending to a File

To append content to an existing file, open the file in append mode ("a").

Example:




Closing a File

Always close files after completing operations to free up system resources.

Example:




Using the with Statement

Using the with statement is a better practice for file handling as it ensures proper resource management.

Example:




Python Labs

Tutorials dojo strip