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.

Modes

Tutorials dojo strip
  • "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:

Python

Reading a File

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

Reading the Entire File:

Python

Reading Line by Line:

Python

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:

Python

Writing Multiple Lines:

Python

Appending to a File

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

Example:

Python

Closing a File

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

Example:

Python

Using the with Statement

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

Example:

Python

Python Labs

Tutorials dojo strip