Contents

Python File Operations

Website Visitors:

Opening, Reading, Writing, and Closing Files in Python

File handling is an essential aspect of programming, allowing us to work with data stored in files. In Python, there are several built-in functions and methods that enable us to open, read, write, and close files efficiently. In this article, we will explore these operations and provide examples to demonstrate their usage.

Opening a File

Before performing any operations on a file, we need to open it using the open() function. The open() function takes two parameters: the file name or path and the mode in which the file will be accessed. The mode can be specified as a string argument and determines whether the file will be opened for reading, writing, or both.

Here is the general syntax for opening a file in Python:

1
file_object = open(file_name, mode)

Let’s look at some examples:

1
2
3
4
5
6
7
8
# Example 1: Open a file in read mode
file1 = open("data.txt", "r")

# Example 2: Open a file in write mode
file2 = open("output.txt", "w")

# Example 3: Open a file in append mode
file3 = open("log.txt", "a")

In Example 1, we open the file “data.txt” in read mode ("r"). This mode allows us to read the contents of the file, but it doesn’t allow us to modify or write to the file.

In Example 2, we open the file “output.txt” in write mode ("w"). This mode opens the file for writing, and if the file doesn’t exist, it will be created. If the file already exists, its contents will be overwritten.

In Example 3, we open the file “log.txt” in append mode ("a"). Append mode allows us to add new content to the end of an existing file. If the file doesn’t exist, it will be created.

Tip
If you are working with windows to open files, you should use the full path with additional backslash as shown below: file = open("C:\\Users\\user01\\Desktop\\text.txt")

Reading a File

Once a file is open for reading, we can access its contents using various methods. The most commonly used methods are readline() and read().

The readline() Method

The readline() method reads a single line from the file and returns it as a string. Each time readline() is called, it moves the file pointer to the next line.

Here’s an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Opening a file in read mode
file = open("data.txt", "r")

# Reading the first line of the file
line1 = file.readline()
print(line1)
# Output: Prints first line in the data.txt file.

# Reading the second line of the file
line2 = file.readline()
print(line2)
# Output: Prints second line in the data.txt file.

# Closing the file
file.close()

In this example, we open the file “data.txt” in read mode and read the first line using readline(). We then print the first line. Next, we call readline() again, and it returns the second line. Finally, we close the file using the close() method.

The read() Method

The read() method reads the entire contents of a file and returns them as a string. It can be used to read the entire file at once or a specified number of characters.

Here’s an example:

1
2
3
4
5
6
7
8
9
# Opening a file in read mode
file = open("data.txt", "r")

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

# Closing the file
file.close()

In this example, we open the file “data.txt” in read mode and use the read() method to read the entire contents of the file. The contents are then stored in the content variable and

printed to the console. Finally, we close the file using the close() method.

Default mode when opening files

The default access mode for opening a file in Python is typically read-only mode, denoted by the letter ‘r’. This mode allows you to read the contents of the file but does not allow modifications or writing to the file.

Here’s an example of how you can open a file using the default read-only mode:

1
file = open('filename.txt')

In this case, the file named “filename.txt” will be opened in read-only mode. Once the file is open, you can read its contents using methods like read(), readline(), or readlines().

Remember to close the file after you’re done with it to free up system resources:

1
file.close()

It’s worth noting that if the file you’re trying to open doesn’t exist, a FileNotFoundError will be raised. If you want to create a new file in write mode (instead of read-only mode), you can specify the ‘w’ mode explicitly.

Writing to a File

When a file is open for writing, we can use the write() method to write data to it. The write() method takes a string as its parameter and writes that string to the file.

If you open a file for writing, all the old contents in the file will be deleted as soon as the file is opened. When write() method is used, content is over written to the file. If the file doesn’t exist, it will create the file automatically when write() method is used. In the output you will get a number which is the return value which says the number of characters it has written to the file.

Here’s an example:

1
2
3
4
5
6
7
8
9
# Opening a file in write mode
file = open("output.txt", "w")

# Writing content to the file
file.write("Hello, World!")
file.write("This is a new line.")

# Closing the file
file.close()

In this example, we open the file “output.txt” in write mode and use the write() method to write two lines of text to the file. The write() method doesn’t automatically add newlines, so if we want to write each line on a separate line, we need to explicitly add newline characters (\n) at the end of each line.

Closing a File

After performing the necessary operations on a file, it’s important to close it using the close() method. Closing a file ensures that any changes made to the file are saved, and it frees up system resources.

Here’s an example:

1
2
3
4
5
6
7
# Opening a file in read mode
file = open("data.txt", "r")

# Perform operations on the file

# Closing the file
file.close()

In this example, we open the file “data.txt” in read mode, perform some operations on the file, and then close it using the close() method. It’s good practice to always close files after you’re done with them to avoid potential issues and resource leaks. But you might not have a track of open files in Python. In order to address this issue we have with keyword. Now lets see what it is.

Closing a file automatically after execution

The with statement in Python is designed to simplify the management of resources that need to be explicitly opened and closed. It ensures that resources are properly released, even if an exception occurs within the block of code.

Syntax and Basic Usage The basic syntax of the with statement is as follows:

1
2
with expression [as target]:
    # Code block

The expression is typically a function or an object that represents the resource being managed. The target is an optional variable that can be used to reference the resource within the block.

Example 1: Opening and Closing Files One of the most common use cases for the with statement is file handling. Let’s see how we can use the with statement to open and close a file:

1
2
3
4
with open("data.txt", "r") as file:
    # Perform file operations
    content = file.read()
    print(content)

In this example, the open() function is used to open the file in read mode. The file object is automatically assigned to the variable file. Within the with block, we can perform file operations, such as reading the content. Once the block is exited, either normally or due to an exception, the file is automatically closed, ensuring proper resource cleanup.

Example 2: Working with Network Connections The with statement is not limited to file handling; it can be used with any resource that requires explicit opening and closing. Here’s an example demonstrating how to use the with statement with a network connection:

1
2
3
4
5
6
7
import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Perform network operations
    sock.connect(("example.com", 80))
    data = sock.recv(1024)
    print(data.decode())

In this example, we create a TCP socket using the socket.socket() function. The with statement ensures that the socket is properly closed after we finish using it, regardless of whether an exception occurs or not.

Example 3: Print all lines in a file

You can iterate through all lines and print using the for loop in with keyword as shown below:

1
2
3
with open("c:\\users\\user01\\Desktop\\text.txt") as file:
    for everyline in file:
        print(everyline)

Above code prints the contents of the file but it also adds empty lines in between it adds the empty lines at the end of each line in the file to the output. In order to remove this, we have to use strip() method.

1
2
3
with open("c:\\users\\user01\\Desktop\\text.txt") as file:
    for everyline in file:
        print(everyline.strip())
Tip
If you use readline with the with keyword, it will always print the first line in the file you specify because after execution that file is closed and when it is run again, it will treat as if it is running for the first time, and read the first line.

Example:

1
2
with open("c:\\users\\user01\\Desktop\\text.txt") as file:
        print(file.readline())

Advantages of Using with

Using the with statement offers several advantages:

a. Automatic Resource Management: The with statement guarantees that resources are properly released, even in the presence of exceptions. It eliminates the need for manual cleanup code, reducing the risk of resource leaks.

b. Readability and Conciseness: The with statement improves code readability by clearly indicating the scope of resource usage. It also eliminates the need for explicit opening and closing of resources, making the code more concise and less error-prone.

c. Context Manager Support: The with statement works with objects that are context managers. A context manager is an object that defines the __enter__() and __exit__() methods, allowing it to be used in a with statement. Many built-in Python objects, as well as third-party libraries, provide context managers for seamless integration with the with statement.

Check if file exists

In python we can check if a file exists using OS module. If file exists we get True output and False when file doesn’t exist.

1
2
import os
os.path.exists("C:\\Users\\user01\\Desktop\\text.txt")

Other file operations

We first have to import os module inorder to work with few other file operations.

import os os.remove(“filename.txt”) - Removes a file. os.rename(“firstname.txt”,“newname.txt”) - Renames a file. os.path.exists(“C:\Users\user01\Desktop\text.txt”) - Check if file exists. os.path.getsize(“file.txt”) - Results the file size in bytes. os.path.getmtime(“file.txt”) - gets the timestamp on when the file was last modified.

To convert it to readable format, you have to convert it using datetime module. import datetime timestamp = os.path.getmtime(“file.txt”) datetime.datetime.fromtimestamp(timestamp)

os.path.abspath(“file.txt”) - gets the absolute path of the file.

Conclusion

Handling files is a crucial skill in Python programming. In this article, we explored the process of opening, reading, writing, and closing files in Python. We learned how to open a file in different modes, read its contents using readline() and read(), write data to a file using write(), and close the file using close().

Remember to handle file operations with care and always close files after you’re done with them. By utilizing these file handling techniques, you can effectively work with external data and perform a wide range of file-related tasks in your Python programs.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.