# file read, write and exception handling Operations Example # date:2017-07-17file_name = "D:/file_demo.txt" with open (file_name, ' W ') as Write_file_obj: ' Write file ' ' Write_file_obj.write ("hello\n") write_file_obj.write ("world\n") with open (file_name, ' a ') as Write_file_obj: ' " Append file ' Write_file_obj.write ' ("!") With open (file_name) as File_obj: "reads the entire contents of the file" "Whole_context = File_obj.read () print (Whole_context.strip ()) Print ('------------------------') with open (file_name) as File_obj: "reads the contents of the file by line" ' for lines in File_obj:print (Line.strip ()) # Remove left and right blank print ('------------------------') with open (file_name) as file_obj: ' list read file contents ' line s = 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 (WHO Le_context.strip ()) except Filenotfounderror:print ("File '" + file_name + "' Not found! ") Else:print ("File" + file_name + "' exists!")
Python file read/write