Python file read and write and exception handling __python

Source: Internet
Author: User
# 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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.