Open a File Using the open() Function in Python

In Python, the open() function is used to open a file and return a file object that allows reading, writing, or appending data.

The open() function takes at least one argument: the file path, and optionally a mode (e.g., read mode 'r', write mode 'w', append mode 'a', etc.). Below, we explore different ways to open a file with examples.

For complete list of parameters that open() function can take, refer Python open() Builtin Function.


Examples

1. Opening a File in Read Mode

To read the contents of a file, we can use the 'r' mode, which is the default mode in Python.

In this example we will open input.txt in read mode, and print its content.

main.py

</>
Copy
# Opening a file in read mode
file = open("input.txt", "r")

# Reading content
content = file.read()

# Printing the content
print(content)

# Closing the file
file.close()

Explanation:

Here, we use the open() function to open a file named input.txt in read mode ('r'). The read() method is used to retrieve the file’s content and store it in the variable content. Finally, we print the content and close the file using file.close() to free system resources.

Output:

2. Opening a File in Write Mode

Using 'w' mode, we can write new content to a file. If the file exists, its content will be overwritten; otherwise, a new file will be created.

In this example, we open output.txt in write mode, and write some text into that file.

main.py

</>
Copy
# Opening a file in write mode
file = open("output.txt", "w")

# Writing to the file
file.write("Hello, World!")

print('Content written to file successfully.')

# Closing the file
file.close()

Explanation:

We use open("output.txt", "w") to open the file in write mode. The write() method writes a string to the file. Finally, we close the file to ensure the changes are saved.

Output:

The file “output.txt” is created or overwritten with the given content.

3. Appending to a File using open()

The 'a' mode is used to append new content to an existing file without overwriting its contents.

main.py

</>
Copy
# Opening a file in append mode
file = open("output.txt", "a")

# Appending text to the file
file.write("\nAppending a new line.")

print('Content added to output.txt successfully.')

# Closing the file
file.close()

Explanation:

The open("output.txt", "a") statement opens the file in append mode. The write() method adds text at the end of the file without deleting the existing content.

Output:

The output.txt file now contains the original text plus the new appended line.

4. Reading a File Line by Line using open() and readlines()

To read a file line by line, we use a loop with the readline() or readlines() method.

main.py

</>
Copy
# Opening a file in read mode
file = open("sample.txt", "r")

# Reading file line by line
for line in file:
    print(line.strip())

# Closing the file
file.close()

Explanation:

We use a loop to iterate through the file object and read each line. The strip() method removes extra whitespace characters like newlines.

Output:

5. Using with Statement to Open Files

The with statement is the recommended way to handle files because it ensures automatic file closure after execution.

main.py

</>
Copy
# Using 'with' statement to open a file
with open("sample.txt", "r") as file:
    content = file.read()
    print(content)  # Printing file content

# No need to explicitly close the file

Explanation:

The with open() syntax ensures that the file is closed automatically when exiting the block, preventing resource leaks.

Output:

Conclusion

In this tutorial, we covered examples for Python’s open() function providing various modes to handle file operations:

  1. 'r' (Read mode): Opens the file for reading.
  2. 'w' (Write mode): Creates or overwrites a file.
  3. 'a' (Append mode): Adds new content without deleting existing data.
  4. with open(): Automatically closes the file after execution.