The open()
function in Python is used to open a file and return a corresponding file object. This function is used for reading, writing, and appending data to files. The syntax is open(file, mode)
, where file is the name (and path) of the file and mode specifies the mode in which the file is opened.
# Open a file in read mode
file = open("example.txt", "r")
# Read the entire content of the file
content = file.read()
print(content)
# Close the file
file.close()
In Python, you can write to a file using the write()
method.
# Open a file in write mode
file = open("example.txt", "w")
# Write some content to the file
file.write("Hello, world!")
# Close the file
file.close()
In Python, you can append to a file using the write()
method with the a
mode.
# Open a file in append mode
file = open("example.txt", "a")
# Append some content to the file
file.write("\nAppended text.")
# Close the file
file.close()
# Open a file in read mode
file = open("example.txt", "r")
# Read and print each line in the file
for line in file:
print(line.strip())
# Close the file
file.close()
The with
statement in Python is used to simplify exception handling by encapsulating common preparation and cleanup tasks in so-called context managers. The with
statement is used to wrap the execution of a block of code within methods defined by a context manager.
The with
statement is commonly used to open files, acquire locks, and more. When the block of code is exited, the context manager's __exit__()
method is called to clean up resources.
# Open a file using the with statement
with open("example.txt", "r") as file:
# Read the entire content of the file
content = file.read()
print(content)
# No need to explicitly close the file; it's done automatically
'r'
- Read mode (default). Opens a file for reading.'w'
- Write mode. Opens a file for writing (creates a new file or truncates an existing file).'a'
- Append mode. Opens a file for appending (creates a new file if it doesn't exist).'b'
- Binary mode. Can be added to other modes (e.g., 'rb', 'wb') for binary files.'t'
- Text mode (default). Can be added to other modes (e.g., 'rt', 'wt').# Open a file in read mode
file = open("example.txt", "r")
# Read the entire content of the file
content = file.read()
print(content)
# Close the file
file.close()