Python File Handling – Tutorial with Examples

File handling is an important aspect of any programming language. It allows you to store, read, and manipulate data stored in a file. Python provides several built-in functions and methods to work with files and directories. In this article, we’ll explore the basics of file handling in Python and cover the following topics:

  • Opening and Closing Files
  • Reading Files
  • Writing to Files
  • Appending to Files
  • Handling File Exceptions

Opening and Closing Files

To work with a file, you first need to open it. You can open a file in Python using the open() function. The open() function takes two arguments: the name of the file and the mode in which you want to open it. The mode can be one of the following:

  • "r" – Read mode (default)
  • "w" – Write mode
  • "a" – Append mode
  • "x" – Exclusive creation mode

Here’s an example of how to open a file in read mode:

f = open("example.txt", "r")

Once you’ve finished working with a file, you should close it to free up system resources. You can close a file in Python using the close() method. Here’s an example:

f.close()

It’s a good practice to use the with statement when working with files. The with statement automatically closes the file for you, even if an exception is raised:

with open("example.txt", "r") as f:
    # do something with the file

Reading Files

Once you’ve opened a file in read mode, you can read its contents using the read() method. The read() method returns the entire contents of the file as a string. Here’s an example:

with open("example.txt", "r") as f:
contents = f.read()
print(contents)

If you want to read the file line by line, you can use the readline() method. Here’s an example:

with open("example.txt", "r") as f:
    line = f.readline()
    while line:
        print(line)
        line = f.readline()

Another way to read the file line by line is to use a for loop. Here’s an example:

with open("example.txt", "r") as f:
    for line in f:
        print(line)

Writing to Files

To write to a file, you need to open it in write mode ("w"). If the file does not exist, it will be created. If the file exists, its contents will be overwritten. Here’s an example of how to write to a file:

with open("example.txt", "w") as f:
    f.write("This is a new line.")

Appending to Files

To append to a file, you need to open it in append mode ("a"). If the file does not exist, it will be created. If the file exists, the data will be appended to the end of the file. Here’s an example of how to append to a file:

with open("example.txt", "a") as f:
    f.write("This is another new line.")

Handling File Exceptions

When working with files, there are several exceptions that you should be prepared to handle. For example, you may try to open a file that does not exist or write to a file that you do not have permission to write to. To handle these exceptions, you can use a tryexcept block. Here’s an example:

try:
    with open("example.txt", "r") as f:
        contents = f.read()
        print(contents)
except FileNotFoundError:
    print("File not found.")
except PermissionError:
    print("You do not have permission to access this file.")

In this example, if the file does not exist, a FileNotFoundError will be raised and the message “File not found.” will be printed. If you do not have permission to access the file, a PermissionError will be raised and the message “You do not have permission to access this file.” will be printed.

That’s it! With these basics of file handling in Python, you should be able to handle most of your file I/O needs. If you have any questions or comments, feel free to leave them in the comments section below.

Leave a Reply

Your email address will not be published. Required fields are marked *