Python Learning-Basics (ix)

Source: Internet
Author: User

read-write files are the most common IO operations. Python has built-in functions for reading and writing files, and the usage is compatible with C.

Try:    f = open (R ' C:\Users\syc\Desktop\temp.txt ')    print f.read () finally:    if f:        F.close ()

The Close method must be executed to read the file, and another method:

With open (R ' C:\Users\syc\Desktop\temp.txt ') as F:    print F.read ()



Python introduces theWithstatement to automatically help us callClose ()method, which is the same as the previous try ... finally , but the code is better and more concise, and you do not have to call the F.close () method

The call to read () reads the entire contents of the file one time, and if the file is 10G, the memory explodes, so to be safe, you can repeatedly call the read (size) method to read the contents of a size byte at most. In addition, call ReadLine () can read a line of content at a time, call ReadLines () to read all of the content one time and return the list by row. Therefore, you need to decide how to call as needed.

If the file is small, read () One-time reading is the most convenient, if the file size cannot be determined, repeated calls to read (size) insurance, if it is a configuration file, call ReadLines () the most convenient:

For line in F.readlines ():    print (Line.strip ()) # Erase the end of ' \ n '



File-like Object

Like the open () function, this object, which has a read () method, is called File-like object in Python. In addition to file, it can be memory byte stream, network stream, custom stream and so on. File-like object does not require inheritance from a particular class, just write a read () method on the line.

Stringio is a file-like Object that is created in memory and is commonly used as a temporary buffer.

The default is to read the text file, and it is an ASCII-encoded text file. To read binary files, than slices, videos, etc., with' RB 'mode to open the file
f = open ('/users/michael/test.jpg ', ' RB ')



to read a non-ASCII encoded text file, it must be opened in binary mode and decoded. Like GBK encoded files.

Python provides a codecs module that helps us to automatically convert the encoding when reading a file, and read the Unicode directly:

Import Codecswith codecs.open ('/users/michael/gbk.txt ', ' r ', ' GBK ') as F:    f.read () # u ' \u6d4b\u8bd5 '



Write a file

Write and read files are the same, the only difference is to call open () function, the incoming identifier ' W ' or WB ' denotes writing a text file or writing a binary file ;

You can call back and forthWrite ()to write to the file, but be sure to callF.close ()to close the file. When we write a file, the operating system often does not immediately write the data to disk, but instead put it in memory cache, and then write slowly when idle. Only CallClose ()method, the operating system guarantees that no written data is written to disk. Forget to callClose ()The consequence was that the data could have been written only part to the disk, the remainder was lost. So, it's still usedWithstatement comes with insurance:

With open ('/users/michael/test.txt ', ' W ') as F:    f.write (' Hello, world! ')



to write to a specific encoded text file, followCodecsFor example, write Unicode, byCodecsautomatically converted to the specified encoding.

in Python, file reads and writes are done through file objects opened by the open () function. Using the WITH statement to manipulate file IO is a good habit.

manipulating files and directories

os module are operating system-related , part of the function for manipulating files and directories is placed in os module, part of os.path module, take note of this. viewing, creating, and deleting a directory can be called this:

Os.path.abspath ('. ') # The absolute path under the current path Os.path.join (' xxx ', ' yyyy ') # When combining two paths, do not spell the string directly, but through the Os.path.join () function, This will correctly handle the path delimiters for different operating systems. Os.mkdir (' xxx ') # Create directory os.rmdir (' xxx ') # Delete directory Os.path.split ('/users/michael/testdir/file.txt ') # ('/users/michael/ TestDir ', ' file.txt ') split directory Os.path.splitext ('/path/to/file.txt ') # ('/path/to/file ', '. txt ') Os.path.splitext () Can directly let you get file extension os.rename (' test.txt ', ' test.py ') # File Rename os.remove (' test.py ') # Delete file



Serialization:

Python provides two modules for serialization:Cpickleand thePickle. The two modules function the same, the difference is thatCpickleIt's written in C, fast,Pickleis written in pure python, slow, withCstringioand theStringioa truth. When you use it, try importing it first .Cpickle, if it fails, then importPickle:

Try:    import cpickle as pickleexcept importerror:    import Pickle




Python Learning-Basics (ix)

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.