Python file read/write

Source: Internet
Author: User

# 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

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.