Python File Handling

Python File Handling

Hello codedamn family, welcome to another exciting blog post. Today, we will be delving into the world of Python file handling. Python, as we know, is a high-level programming language that is widely used in web development, AI, machine learning, operating systems, mobile application development, and some big games. Python provides several functions for creating, reading, updating, and deleting files, and in this blog, we will explore these functions in depth.

Understanding File Handling

File handling is a standard feature of any programming language. It allows a language to interact with files on your system. These interactions can be creating a new file, reading content from a file, writing content to a file, or appending new content to an existing file. In Python, file handling is done using a built-in module called 'os' and built-in functions like open(), read(), write(), and close().

Opening a File in Python

In Python, a file is opened using the built-in open() function. This function takes two parameters – the name of the file and the mode in which the file is opened. There are four modes in Python:

  1. "r" – Read: Opens the file for reading. The file must exist.
  2. "w" – Write: Opens the file for writing. Creates a new file if it does not exist, or truncates the file if it exists.
  3. "a" – Append: Opens the file for appending. The file is created if it does not exist.
  4. "x" – Create: Creates the specified file. Returns an error if the file exists.
file = open("myfile.txt", "r")

Reading a File in Python

Once a file is opened in read mode, we can read its contents using the read() function. This function reads the entire content of the file as a single string. If you want to read a file line by line, use the readline() function or a for loop.

file = open("myfile.txt", "r") print(

Writing to a File in Python

To write to a file in Python, we open the file in write "w" or append "a" mode. We then use the write() function to write to the file. Remember, the write() function will overwrite any existing content in the file.

file = open("myfile.txt", "w") file.write("Hello, codedamn!")

Closing a File in Python

Closing a file when you're done with it is a good practice. It frees up system resources. To close a file, use the close() function.

file = open("myfile.txt", "r") print( file.close()

Working with Directories in Python

Python's os module provides numerous methods to perform directory-related operations. For example, you can create a new directory, rename a directory, list all files in a directory, and so on.

import os os.mkdir("mydirectory")

Exception Handling in Python File I/O

Just like any other code, file I/O operations can also raise exceptions. A common exception when working with file read operation is the FileNotFoundError. It's always a good idea to handle these exceptions.

try: file = open("non_existent_file.txt", "r") except FileNotFoundError: print("The file does not exist")


Q: What is the difference between 'w' and 'a' modes?

A: The 'w' mode overwrites the file if it exists and creates a new one if it doesn't. The 'a' mode appends to the file if it exists and creates a new one if it doesn't.

Q: Do I always need to close a file after opening it?

A: It is a good practice to close a file after you're done with it. However, if you open a file using the 'with' statement, Python will automatically close it for you.

Q: How can I read a file line by line in Python?

A: You can read a file line by line using the readline() function or by iterating over the file object in a for loop.

For further reading, please refer to the official Python documentation on file handling here. Happy coding, codedamn developers!

Sharing is caring

Did you like what Rishabh Rao wrote? Thank them for their work by sharing it on social media.


No comments so far