Python provides different ways to open and use files. The open()
method is used to open a file in a traditional way and then close the file with the close()
method.
Opening File Conventionally
By default open() method is used to open a file and close() method is used to close the file in a conventional way. file operations may create some errors or exceptions which crash the script.
f = open("data.txt")
data = file.read()
print(data)
f.close()
Opening File Using with Statement
The with
statement can be used to work with a file by opening, reading, and writing it. The advantage of using with statement is there is no need to close a file which is done implicitly. The file operation code is written inside the with statement block. The syntax of the with statement for file operations is like below.
with open(FILE):
FILE OPERATIONS
In the following example, we read the file contents and print them to the screen.
with open("data.txt"):
data = file.read()
print(data)