practical notes file handling -2

Using open in Python without with

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top