Python Learning Note (ix)-IO programming

Source: Internet
Author: User

I. File read and write:

1. Read the file:

Try:    f = open (' D:\\1.txt ', ' R ') # reads plain file    f = open (' d:\\1.jpg ', ' RB ') # reads binary file    f.read () finally:    if f:
   
    f.close () with open (' D:\\1.txt ', ' R ') as F: # using with will automatically call close for lines in    f.readlines (): # readlines can read a line of        print (Line.strip ()) # Delete the "\ n" at the end of the        import codecswith codecs.open (' D:\\1.txt ', ' r ', ' GBK ') as F: # Use Codecs to specify the encoding for    Li NE in F.readlines ():         
   
2. Write the file:
f = open (' D:\\1.txt ', ' W ') # Write bits wbf.write (' Hello, world! ') F.close ()

Two. operating files and directories:

Python's OS module encapsulates the operating system's directory and file operations, note that some of these functions are in the OS module, some in the Os.path module

Import Osprint Os.environ # Gets the operating system environment variable print os.getenv (' path ') # Gets the value of path in the environment variable print os.path.abspath ('. ') # View the absolute path of the current directory # Os.mkdir (' D:\\test ') # then create a directory #os.rmdir (' d:\\test ') # Delete a directory of print os.path.join (' d:\\test ', ' TT ') # combine two paths into one d:\test\ Ttprint os.path.split (' D:\\test\\1.txt ') # Split path (' D:\\test ', ' 1.txt ') print os.path.splitext (' d:\\test\\1.txt ') # Get Extended Name (' d:\\test\\1 ', '. txt ')

Three. Serialization


Python Learning Note (ix)-IO programming

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.