All about files in python 📁
file = open('test.py')
This above code will give error, if no test.py file is present.
file = open('test.py', 'w')
This above code will find the test.py file first, if found, its good, if not, then it will first create a test.py file and then open it. Thats why, we need to use this with caution, and use try finally.
file = open('kismat.txt', 'w')
# method 1
try:
file.write('Grinding Harder than before')
finally:
file.close()
# method 2
with open('kismat.txt', 'w') as file:
file.write('Grinding Harder than before')
Method 1 Advantages:
Offers explicit control over file operations.
Useful in scenarios where more complex operations are needed within the try block.
Method 1 Disadvantages:
More verbose.
Increased likelihood of forgetting to close the file.
Method 2 Advantages:
Concise and cleaner syntax.
Automatic handling of file operations, reducing the chance of mistakes.
Method 2 Disadvantages:
- Less explicit control over file operations (may be a disadvantage in specific situations).