Python Learning note __9.1 file read and write

Source: Internet
Author: User

# This is a learning note for the Liaoche teacher Python tutorial

1. Overview

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.

The ability to read and write files on disk is provided by the operating system, and the modern operating system does not allow the normal program to manipulate the disk directly, so the read-write file is requested by the operating system to open a file object (often referred to as a file descriptor) and then read the data from the file object (read file) through the interface provided by the operating or write the data to this file object (write file).

1.1. Get the File object

Use the Python built-in open () function to pass in file names and identifiers. Can get file objects

>>> f = open ('/users/michael/test.txt ', ' R ')

    • file name: file names generally write absolute paths. Be sure to use / separate

    • identifiers: R table Read-only, W table Overwrite Write, a table Append. Different file types, there are also different identifiers

Identifier Classification (Https://docs.python.org/3/library/functions.html#open)

1.2. Call method

After the file object gets, we can use the corresponding method according to the passed identifier.

1 ) R

F.read ()

Calling read () reads the entire contents of the file one time, and if the file is too large, 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 each time, call readlines () to read all of the content one time and return the list by row

For line in F.readlines ():

Print (Line.strip ()) # Erase the end of ' \ n '

2 ) W

>>> f = open ('/users/michael/test.txt ', ' W ') # W is overwrite the original content, write new content

>>> F.write (' Hello, world! ') # f.write () can be called multiple times

3 ) f.close ()

Whether we read it or write it. You must close the file when you are finished using it. Because the file object consumes the resources of the operating system, the number of files that the operating system can open at the same time is limited.

and when we write files, the operating system often does not immediately write the data to disk, but put it into memory cache, idle time and then slowly write. Only when the close () method is called does the operating system guarantee that all data that is not written is written to disk.

IOError can be generated when a file is read and written, and F.close () will not be called once an error occurs. So, we have two ways to make sure that the file is closed correctly, whether it's wrong or not.

Method One: Try ... finally to achieve:

Try

f = open ('/path/to/file ', ' R ')

Print (F.read ())

Finally

If f:

F.close ()

Method Two: The With statement automatically calls the close () implementation

with open ('/path/to/file ', ' R ') as F: # when the operation is complete, with automatically called f.close ()

print (F.read ())

1.2. File-like Object

like the Open () function returns an object of this kind that has a read () method, called in Python file-like Object .

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.

1 ) binary file

Identifier B: Represents a binary file

>>> f = open ('/users/michael/test.jpg ', ' RB ')

>>> F.read ()

B ' \xff\xd8\xff\xe1\x00\x18exif\x00\x00 ... ' # Hexadecimal representation of bytes

2 ) character encoding

to read a text file that is not UTF-8 encoded, you need to pass in the open () function Encoding Parameters

>>> f = open ('/users/michael/gbk.txt ', ' R ', encoding= ' GBK ')

>>> F.read ()

Test

Some file encodings are not canonical and may encounter Unicodedecodeerror. Use the error parameter to ignore errors

>>> f = open ('/users/michael/gbk.txt ', ' R ', encoding= ' GBK ', errors= ' ignore ')


Python Learning note __9.1 file read and write

Related Article

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.