1# file handling
2
3# 1) without using with statement
4file = open('file_path', 'w')
5file.write('hello world !')
6file.close()
7
8# 2) without using with statement
9file = open('file_path', 'w')
10try:
11 file.write('hello world')
12finally:
13 file.close()
14
15# using with statement
16with open('file_path', 'w') as file:
17 file.write('hello world !')
1# using with statement in python
2with open('file_path', 'w') as file:
3 file.write('hello world !')
4
1In python if you want to operate some file then you have to use some specific function for that after using that we can read or manipulates the data of the file.
2And for operating the file we use open() function. open returns the file object, from which we can access functions and attributes for performing file operation by opening the file.
3
4In the normal file operation we have to follow some rules, like opening the file using 'open()' method then read the file data using 'read()' method after that print the data of file and when all operation gets over we need to close the file using 'close()' method.
5Example:
6file = open('abc.txt')
7data = file.read()
8print data
9file.close() #file closing is must or it will throw error
10
11Using with statement we can get automatic exception handelling and better syntax.
12at the end there is no need of write closing of file it automatically get space cleared by with statement.
13Example:
14with open('abc.txt') as file: # refer file as object for file object
15data = file.read()
16print data
17
18or
19 file.write('Hello python')
20
21you can check we not included file close method in the with statement program.
22Done!!!
1The 'with' statement is a new control-flow structure whose basic structure is:
2
3with expression [as variable]:
4 with-block