Opening a file in read mode:
- After working with any resource(file, database, server…) from the application must be released manually(closing statements)
- Improper shutdown of resources results loss of data.
Code:
class Process:
file = None
def main():
try :
Process.file = open("./script.py", "r")
print("File opened in read mode")
except FileNotFoundError:
print("Exception : No such file to open")
finally:
if Process.file != None:
Process.file.close()
print("File closed")
return
Process.main()
Reading information from the file:
- read() method is belongs to File object.
- Once the file has opened successfully, we need to call read() method on file object.
- read() method returns the complete content of file as an object.
- We can display the complete content of that data object in a single instance
class Process:
file = None
def main():
try:
Process.file = open("./script.py", "r")
print("File opened")
data = Process.file.read()
print(data)
except FileNotFoundError:
print("Exception : No such file")
finally:
if Process.file != None:
Process.file.close()
print("File closed")
return
Process.main()