# Examples of file read, write, and exception handling operations # DATE:2017-07-17 file_name = "D:/file_demo.txt" with open (file_name, ' W ') as Write_file_obj: ' Write into file ' Write_file_obj.write ("hello\n") write_file_obj.write ("world\n") with open (file_name, ' a ') as Write_file_ob
J: ' Append file ' Write_file_obj.write ("!")
With open (file_name) as file_obj: ' Read all file contents ' Whole_context = File_obj.read () print (Whole_context.strip ())
Print ('------------------------') with open (file_name) as file_obj: ' Read the contents of the file line by row ' for lines in File_obj: Print (Line.strip ()) # to remove the left and right space print ('------------------------') with the Open (file_name) as File_obj: ' List of files read
Content ' lines = File_obj.readlines (); For line in Lines:print (Line.strip ()) # Remove left and right space print ('------------------------') file_name = "D:/file_demo
_none.txt ' Try: ' Exception handling: file does not exist ' with open (file_name) as File_obj:whole_context = File_obj.read () Print (Whole_context.strip ()) except FilenotfoundeRror:print ("File" + file_name + "' Not found!")
Else:print ("File" + file_name + "' exists!")
Run Result:
Hello
world
!
------------------------
Hello
world
!
------------------------
Hello
world
!
------------------------
File ' d:/file_demo_none.txt ' not found!