The IO operation of the Python Advanced trilogy

Source: Internet
Author: User
Tags readline

IO programming file read/write Open file

open(file, mode=‘r‘, buffering=None, encoding=None, errors=None, newline=None, closefd=True)To see the API in particular, here are just a few common methods.

The file name of the Open function is a required parameter, which returns a Document object

#打开一个文件。f = open(‘read.txt‘, ‘r‘)
of the Open function ModeParameters:
value function Description
' R ' Read mode
' W ' Write mode
A Append mode
' B ' Binary mode
+ Read/write mode

b parameter when processing a text file is less than the B parameter, but processing other types of files (binary files,) such as MP3 or images, then should be added in the schema parameter B

Buffering, File buffer:

Buffer, the default is no buffer,

    1. If the parameter is 0,io operation is no buffer, write data directly on the hard disk,

    2. If the parameter is a 1,io operation is buffered, the data is written into memory, only the use of the flush function, or the close function, the data will be updated to the hard disk,

    3. If the argument is greater than days, it indicates the size of the buffer (in bytes), 1 (or any negative number) that represents the size of the default buffer used.
File reads,
    1. File reads are mainly divided into bytes read and read by line, commonly used methods are read (), ReadLines (), Close ()

    2. If the text file is opened successfully, the next call to the Read () method is to write the contents of the file all in memory at once, and finally return the object of type str:
      F.read ()

    3. Call Close () to close a reference to a file that must be closed after it is used, because the file object consumes system resources and affects system IO operations.

The following close () method will not be called when an IO exception occurs because of an IO exception in the file operation. So in order to ensure the robustness of the program, we need to use try...finally to achieve.

try:    f = open(‘read.txt‘, ‘r‘)    print(f.read())finally:    if f:        f.close()

Python provides a simple way to use the WITH statement instead of the try...finally code block and the Close () method.

with open(‘read.txt‘, ‘r‘) as fileReader:    print(fileReader.read())

Due to the possibility of large files, there will be insufficient memory, Python provides a more reasonable way to call ReadLine () to read a line of content each time.

    • Small files can be read directly into memory by taking the read () method.
    • A more secure way to make large files is to use read (size) continuously
    • For text files such as configuration files, it is more reasonable to use ReadLine ().
with open(‘read.txt‘, ‘r‘) as fileReader:    for line in fileReader.readlines():        print(line.strip())得到结果:123456789        
File Write

Recommended wording:

with open(‘read.txt‘, ‘w‘) as fileWriter:    for num in range(1, 100):        fileWriter.write(str(num)+‘\n‘)

The IO operation of the Python Advanced trilogy

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.