File handling in python?

File handling in python?

File Handling in Python: A Complete Guide with Examples

File handling is an essential feature in Python that allows you to read, write, and manipulate files. Python provides built-in functions and methods for working with files, making it easy to handle file operations, such as opening, reading, writing, and closing files.

In this guide, we will explore how to handle files in Python using the open() function and other associated methods. We will also look at different modes for file operations and common use cases with examples.


Opening a File in Python

In Python, you use the open() function to open a file. It returns a file object, which you can use to perform various file operations.

# Opening a file in read mode
file = open("example.txt", "r")

The open() function takes two arguments:

  1. The name of the file (in this case, example.txt).
  2. The mode in which you want to open the file.

The most commonly used file modes are:

  • '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 one).
  • 'a': Append mode – Opens the file for appending content at the end.
  • 'b': Binary mode – Used for binary files (e.g., images, videos).

Reading from a File

Once a file is opened in read mode, you can read its contents using methods like read(), readline(), and readlines().

Using read()

The read() method reads the entire file's content.

# Opening a file in read mode
file = open("example.txt", "r")

# Reading the content of the file
content = file.read()
print(content)

# Closing the file
file.close()

Using readline()

The readline() method reads the file line by line.

# Opening the file
file = open("example.txt", "r")

# Reading the first line
first_line = file.readline()
print("First line:", first_line)

# Reading the next line
second_line = file.readline()
print("Second line:", second_line)

# Closing the file
file.close()

Using readlines()

The readlines() method reads all lines of the file and returns them as a list.

# Opening the file
file = open("example.txt", "r")

# Reading all lines into a list
lines = file.readlines()
print("All lines:", lines)

# Closing the file
file.close()

Writing to a File

You can write to a file using the write() method in write mode ('w') or append mode ('a'). If the file doesn't exist, Python creates a new one.

Using write()

# Opening a file in write mode
file = open("newfile.txt", "w")

# Writing content to the file
file.write("Hello, this is a new file created by @PythonBeeTelugu.")

# Closing the file
file.close()

In the above example, we opened the file in write mode and wrote a string to it. If the file already exists, it will be overwritten.

Using writelines()

The writelines() method writes a list of strings to a file.

# Opening a file in write mode
file = open("newfile.txt", "w")

# Writing multiple lines at once
lines = ["First line of the file\n", "Second line of the file\n"]
file.writelines(lines)

# Closing the file
file.close()

Appending to a File

If you want to add new content to the end of an existing file without overwriting the original content, you can open the file in append mode ('a').

# Opening the file in append mode
file = open("newfile.txt", "a")

# Appending new content
file.write("This is a new line added by @PythonBeeTelugu.")

# Closing the file
file.close()

File Handling Using with Statement

It's a good practice to use the with statement when working with files in Python. The with statement ensures that the file is properly closed after the block of code is executed, even if an error occurs.

# Using 'with' to open and read a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

The with statement automatically closes the file once the block of code is finished, saving you from having to call file.close() explicitly.


Checking if a File Exists

Before performing any file operation, it's a good idea to check if the file exists. You can use the os module for this.

# Checking if a file exists
import os

if os.path.exists("example.txt"):
    print("File exists!")
else:
    print("File does not exist.")

File Handling with Exception Handling

It's important to handle exceptions when working with files. For example, a file might not exist, or you might not have permission to access it. You can use a try and except block to handle these errors.

  
    try:
        # Attempting to open a non-existing file
        file = open("non_existing_file.txt", "r")
    except FileNotFoundError:
        print("The file does not exist.")
    else:
        content = file.read()
        print(content)
        file.close()
  

Conclusion

File handling in Python is straightforward and allows you to perform a variety of operations, from reading and writing files to handling exceptions. Understanding the basics of file handling—such as using the open() function, reading content, and writing to files—will allow you to work efficiently with data stored in files.

Comments