Python's File Open () method use detailed

Source: Internet
Author: User

Python has a built-in open () method for reading and writing local files. This function is simple and practical, and belongs to the basic knowledge that must be mastered.

Using the Open method to manipulate the file can be divided into three steps, one is to open the file, the second is the operation of the file, three is to close the file. The following are respectively described:

First, open the file

Its basic syntax: F = open (' filename ', ' open mode ')

Open mode:

R read-only default mode, if the file does not exist on the error, there is a normal read.

W write only if the file does not exist, create a new file, then write it, and if it exists, clear the contents of the file before writing.

A append if the file does not exist, create a new file, and then write to it, if present, append the last write to the file.

X write only if the file exists error, if it does not exist, create a new file, and then write content, more secure than W mode. Python3 above new.

+ read-write mode such as r+ w+ A + (detailed below)

b binary mode such as RB WB AB This is related to bytes type, string type (detailed below)

And the combination of R+b w+b a+b, not listed

  Special emphasis:

 1. b mode : binary mode, i.e. 01010101 bit stream. It is important to note that it reads and writes as a byte type (bytes) when read and write, and therefore obtains a byte object instead of a string. In this reading and writing process, you need to specify the encoding format of the byte type. Take the Write () method as an example, and the Read () method is the same.

s ='This is a test'b= Bytes (s,encoding='Utf-8') F= Open ('Test.txt','W') F.write (s)##这样没问题, the file is written normally. ##-------------------------------------------------s ='This is a test'b= Bytes (s,encoding='Utf-8') F= Open ('Test.txt','WB')##注意多了个bF.write (s)##报错Typeerror:a Bytes-like Object isRequired not 'Str'##意思是它需要一个bytes类型数据, you gave me a string.##---------------------------------------------------s ='This is a test'b= Bytes (s,encoding='Utf-8') F= Open ('Test.txt','WB')##注意多了个bF.write (b)##将变量b传给它, B is a bytes type.##成功执行! 

Therefore, be sure to pay attention to the incoming data type when using a pattern with B. No b is read-write in characters, and B is read-write in bytes.

  2. + mode : For w+, in fact this mode, before reading and writing will empty your file content, please do not use!

For a + mode, in fact this mode, you can always only write at the end of the file, there are limitations, please do not use!

For r+ mode, the best read and write mode, with the Seek () and the Tell () method, can achieve most of the operation.

Ii. Methods of file operation

In Python3, the basic file operation methods are:

classTextiowrapper (_textiobase):defClose (self, *args, * *Kwargs): Close FilePass    defFileno (self, *args, * *Kwargs): File descriptorPass    defFlush (self, *args, * *Kwargs): Flush the file internal bufferPass    defIsatty (self, *args, * *Kwargs): Determine if the file is consent to the TTY devicePass    defRead (self, *args, * *Kwargs): reads the specified byte dataPass        defReadable (self, *args, * *Kwargs): readablePass    defReadLine (self, *args, * *Kwargs): Read only one row of dataPass    defSeek (self, *args, **kwargs):#specify pointer position in filePass    defSeekable (self, *args, * *Kwargs): Whether the pointer is operablePass    defTell (self, *args, * *Kwargs): Get pointer positionPass    defTruncate (self, *args, * *Kwargs): Truncate the data, preserving only the previous data specifiedPass    defWritable (self, *args, * *Kwargs): writablePass    defWrite (self, *args, * *Kwargs): Write contentPass    def __getstate__(Self, *args, * *Kwargs):Pass    def __init__(Self, *args, * *Kwargs):Pass@staticmethoddef __new__(*args, **kwargs):#Real Signature Unknown        """Create and return a new object. See Help (type) for accurate signature. """        Pass    def __next__(Self, *args, * *Kwargs):"""Implement Next (self)."""        Pass    def __repr__(Self, *args, * *Kwargs):"""Return repr (self)."""        PassBuffer= Property (LambdaSelf:object (),LambdaSelf, V:none,LambdaSelf:none)#defaultclosed= Property (LambdaSelf:object (),LambdaSelf, V:none,LambdaSelf:none)#defaultencoding= Property (LambdaSelf:object (),LambdaSelf, V:none,LambdaSelf:none)#defaultErrors= Property (LambdaSelf:object (),LambdaSelf, V:none,LambdaSelf:none)#defaultline_buffering= Property (LambdaSelf:object (),LambdaSelf, V:none,LambdaSelf:none)#defaultname= Property (LambdaSelf:object (),LambdaSelf, V:none,LambdaSelf:none)#defaultnewlines= Property (LambdaSelf:object (),LambdaSelf, V:none,LambdaSelf:none)#default_chunk_size= Property (LambdaSelf:object (),LambdaSelf, V:none,LambdaSelf:none)#default_finalizing= Property (LambdaSelf:object (),LambdaSelf, V:none,LambdaSelf:none)#default

Among them, what is really important, need is read, ReadLine, ReadLines, write, tell, seek, flush, close these several methods. Note that there is no way to directly modify the contents of the file. Here are some of the key approaches :

1.read (): You can specify the number of reads, such as F.read (10). If open mode does not have B, read reads in characters and B is read in bytes.

2.write (): If the open mode does not have B, the normal string is accepted as the argument, and if there is b it is required to pass in an object of type bytes.

3.readline (): Reads a row, returns a row of strings if the open mode does not have B, or returns the bytes type if there is b. You can specify a quantity parameter.

4. ReadLines (): reads all files in rows, if open mode does not have B, returns a list of elements consisting of each row string , and if B, returns a list of the bytes types of the rows. You can specify a quantity parameter.

5.tell (): In the open file, maintain a position pointer, the default is initially at the top of the file, that is, 0 position, in the process of reading, read how much, the pointer will move how much, and it is always counted in bytes. So in use must pay attention to the problem of coding, otherwise prone to read and write garbled. The Tell method can get the position of the current pointer, using the method, F.tell ().

6.seek (): Points the pointer to the specified subscript, used in bytes. Method of Use, F.seek (5).

7.flush (): Flushes the freshly written content to a local file. By default, when a file is closed, the data in the cache is written to the local file, which can cause inconsistent data access.

Third, close the file

In order to prevent resource leaks and file corruption, we will close the file every time we finish working on the file. It's simple, the file handle. Close () is fine.

Iv. with-Context Manager

Python's with syntax is great, it helps you automatically close open files without requiring you to call the close () method manually.

The basic use of with IS as follows:

With open (' Test.txt ', ' W ') as F:

F.write (' str ')

And in a later version of 2.7, it also supports opening multiple files at the same time.

    with open(‘log1‘) as obj1, open(‘log2‘) as obj2:

       passWith can not only manage files, but also manage other objects. V. Iteration of the document

After the file is opened, you can iterate through the files in a progressive line:

For line in F:

Pass

Python's File Open () method use detailed

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.