Detailed introduction to Python file reading operations

不言
Release: 2018-10-09 16:29:30
forward
2715 people have browsed it

This article brings you a detailed introduction to Python file reading operations. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Operation steps for reading files

There is a brain teaser, asking the steps to put the elephant into the refrigerator. The answer is very simple, open the refrigerator, put the elephant Push it in and close the refrigerator. This is an idea for dealing with the problem. Our operation on the file is the same. The first step: open the file; the second step: process the file (read or write); the third step is to close the file. How about it? It's actually very simple. Let's talk about the file operation in detail.

Open a file

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Copy after login

To open a file, you need to use the open() function. The parameters involved in () only need to know three parameters in the initial stage. Then It is file, mode, and encoding

file

#The first is the file name, the type is a string, and the path must be included. If the file to be opened is in the same file as the current file In a directory, you can omit the path (relative path).

mode

Then the mode for opening the file, the format is: mode='mode', here " mode=" can be omitted, just write the mode directly. If the mode is not specified, it defaults to r. The specific mode is as follows:
Here introduces a pseudo noun - pointer. Imagine that when you edit text in word, there is Cursor? You can think of the pointer as the cursor, where all your operations on the file start.

r 
只读。文件的初始指针在文件的开头。这是默认模式。
rb
只读的二进制格式。文件的初始指针在文件的开头。
r+
读写。文件的初始指针在文件的开头。
rb+
读写的二进制格式。文件的初始指针在文件的开头。
w
只写。如果该文件已存在则打开文件,清空文件内容。如果该文件不存在,则创建新文件。
wb
只写的二进制格式。如果该文件已存在则打开文件,清空文件内容。如果该文件不存在,创建新文件。
w+
写读。如果该文件已存在则打开文件,清空文件内容。如果该文件不存在,创建新文件。
wb+
写读的二进制格式。如果该文件已存在则打开文件,清空文件内容。如果该文件不存在,创建新文件。
a
追加写。如果该文件存在,文件的初始指针在文件的结尾。新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab
追加写的二进制格式。如果该文件存在,文件的初始指针在文件的结尾。新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+
追加写读。如果该文件已存在,文件的初始指针在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+
追加写读的二进制格式。如果该文件已存在,文件的初始指针在文件的结尾。如果该文件不存在,创建新文件用于读写。
Copy after login

encoding

The third parameter is the encoding of the file (used in non-binary format). The encoding setting must be consistent with the encoding of the file to be opened, otherwise An error will be reported, which means that the source file is written in what encoding, and you have to use what encoding to open it when you open it.

Processing files

Let’s give an example of an error. The operation to be implemented is to open a file named "test". The original file encoding is utf-8. , and we used gbk encoding when opening.
There is only one sentence in the document: Kill one person in ten steps, and leave no trace in a thousand miles.
The code is as follows:

file = open('test','r',encoding='gbk')
content = file.read()
print(content)
file.close()
Copy after login

Here are the following instructions. The result returned by the open function is a file object, so we need to use a variable to receive it (file),
so that we can use this object conveniently methods, such as file.read(), file.write, file.flush(), etc.
read() is a method of the file object. Its function is to read the specified number of characters. If not specified, it will read by default. Get all the content
But an error will be reported after the above code is executed. The following is the error message. The main idea is that the gbk encoding cannot be decoded (the process of opening the file is actually the decoding process)

    ---------------------------------------------------------------------------

    UnicodeDecodeError                        Traceback (most recent call last)

    <ipython-input-78-bb879f008680> in <module>()
          4 #这里说明以下,open函数返回的结果是一个文件对象,所以要用一个变量接收一下(file),这样我们就可以方便地使用这个
          5 #对象的方法了,比如file.read(),file.write,file.flush()等等
    ----> 6 content = file.read()#read()是文件对象的一个方法,作用是读取指定的字符数,如果未指定则默认读取所有内容
          7 print(content)
          8 file.close()

    UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 4: illegal multibyte sequence
Copy after login

The solution is very simple. Just change the encoding method to utf-8. Because the Linux system defaults to utf-8 encoding, the encoding can be omitted. And because we just want to read the file, the mode is r, and the default mode is r. You can also omit it.
So the code becomes the following:

file = open('test')
content = file.read()
print(content)
file.close()
输出为:
十步杀一人,千里不留行
Copy after login

You can also add numeric parameters to the method read(), which is used to specify the number of characters to be read, whether it is Chinese characters or letters, one character corresponds to one letter Or Chinese characters, which must be distinguished from bytes. The example is as follows:

file = open('test')
content = file.read(3)
print(content)
file.close()
输出为:
十步杀
Copy after login

The way we used to open the file before was more troublesome because we had to write a statement to close the file at the end. Here is a simple way The method, the format is:

with open() as file_name:
    操作代码......
Copy after login

The advantage of using this method is that there is no need to write a statement to close the file. with and as are keywords, just remember the format.
Next we create a binary format The file

with open('二进制','wb') as file: 
    file.write('十步杀一人,千里不留行'.encode('utf8'))
Copy after login

Because the way we open the file is in binary format, then when writing the file, we must write a string in binary format, but for "Kill a person in ten steps, leave no trace in a thousand miles" "What is the binary format of this string? We don't know, so we use .encode(utf8) to convert this string into binary format. In fact, we can know the binary format corresponding to this string through another piece of code. The code is as follows:

print('十步杀一人,千里不留行'.encode('utf8'))
输出的二进制格式(表现形式为16进制,为什么?因为二进制太长了啊!!!)为:
b'\xe5\x8d\x81\xe6\xad\xa5\xe6\x9d\x80\xe4\xb8\x80\xe4\xba\xba\xef\xbc\x8c\xe5\x8d\x83\xe9\x87\x8c\xe4\xb8\x8d\xe7\x95\x99\xe8\xa1\x8c'
Copy after login

在实际中我们当然不可能写这么长的东西,所以我们使用.encode('utf8')来转化。转化时我们使用了utf-8的编码方式。
在这里说明一下为什么要编码,想弄清楚这件事就要明白计算机的存储原理。
简单地讲,文件在计算机中都是以二进制格式存储的,对于计算机来讲只有两个数字有意义,那就是0和1,也就是二进制,而不同的0和1的组合代表不同的含义(编码不同),比如在gbk编码下一个汉字由两个字节表示,也就是16位二进制数(16个0和1的组合),而在utf-8编码下一个汉字由3个字节表示,也就是24位二进制数(24个0和1的组合),而我们现在要给计算机存储的就是0和1的组合,那么在读取文件或者转化字符串时,如果你不告诉计算机你使用的是哪种编码的话,计算机怎么可能知道这些0和1的组合代表什么含义呢?所以从计算机取出数据或者把普通字符串转化成二进制格式时你必须告诉计算机你使用的是什么编码方式。
在本例中使用utf-8编码,所以在字符串后面加上.encode(utf8)

那么为什么平时可以直接写入普通字符串呢?那是因为在用open()函数打开文件的时候就已经指定了编码方式。
形象地解释:open函数相当于打开了一种通道,平时打开时都是用某种编码的方式打开的,所以我们在写入内容时不必管它以什么编码进入通道的(因为在open函数里面就已经指定了编码方式)
而当open函数使用二进制格式打开时(就是带b的模式),这个通道就没有指定编码方式,通道里面只有二进制,所以此时往通道里面放入非二进制格式内容的话就需要指定一种编码方式。除非你直接在file.write()函数中直接写二进制,但是人类是不可能记住那么多二进制组合所代表的含义的。

然后我们来读取一下上面创建的名字为“二进制”的这个文件

with open('二进制','rb') as file:
    print('不指定解码方式时的结果:',file.read())
Copy after login

如果我们在读取时不指定解码方式,那么输出的结果就是下面这种人类无法理解的奇怪的东西(实际上它是用16进制表示的二进制)

不指定解码方式时的结果: b'\xe5\x8d\x81\xe6\xad\xa5\xe6\x9d\x80\xe4\xb8\x80\xe4\xba\xba\xef\xbc\x8c\xe5\x8d\x83\xe9\x87\x8c\xe4\xb8\x8d\xe7\x95\x99\xe8\xa1\x8c'
Copy after login

所以我们在读取时也要指定编码:

with open('二进制','rb') as file:
    content = file.read()
    print('指定解码方式后的结果:',content.decode('utf-8'))

指定解码方式后的结果: 十步杀一人,千里不留行
Copy after login

其他的在读取时可能用到的方法:

readline()读取一行,如果里面添加了参数n,则会读取n个字符(我觉得这是个bug,貌似没什么卵用)
readlines()读取所有内容,结果返回一个列表,元素由每一行组成。
tell()会输出当前指针的位置,注意,该位置是以字节来计算的,不是字符
seek()重新指定指针位置。
Copy after login

使用readlines()并不是一个好方法,因为是一次性将文件都读取到内存中,如果文件较大时则造成内存溢出,实际中使用下面的方法,系统会自动生成一个迭代器,用迭代的方法把需要的数据取出来。

with open('libai') as f:
    for i in f: #这里的i实际就是迭代后的每一行,用for循环的方式从文件对象中取出来,取一行读一行,节省内存
        print(i)
Copy after login
赵客缦胡缨,吴钩霜雪明。银鞍照白马,飒沓如流星。

十步杀一人,千里不留行。事了拂衣去,深藏身与名。

闲过信陵饮,脱剑膝前横。将炙啖朱亥,持觞劝侯嬴。

三杯吐然诺,五岳倒为轻。眼花耳热后,意气素霓生。

救赵挥金锤,邯郸先震惊。千秋二壮士,烜赫大梁城。  

纵死侠骨香,不惭世上英。谁能书阁下,白首太玄经。
Copy after login

关闭文件

如果用with open() 来打开文件的话就不用管关闭文件的操作了,因为Python已经帮你完成了这一步,否则必须在处理文件之后加上关闭文件的操作:file_name.close()


The above is the detailed content of Detailed introduction to Python file reading operations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!