Using open in Python without with
In Python, you can use the open()
function without the with
statement as well. However, you must remember to close the file manually using file.close()
. Here’s an example:
# Open a file for writing
file = open('example.txt', 'w')
file.write('This is a test.')
file.close()
# Open a file for reading
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
This approach requires you to manage the file’s closing yourself, which is why using a with
statement is generally preferred for better resource management.