How to read and write files in python

步履不停
Release: 2019-07-03 10:01:33
Original
7680 people have browsed it

How to read and write files in python

Contents of this section:


  1. Overview of I/O operations

  2. File reading Writing implementation principles and operation steps

  3. File opening mode

  4. Python file operation step example

  5. Python file reading related methods

  6. File reading and writing and character encoding

1. Overview of I/O operations


I/O in computers refers to Input/Output, which is the input and output of Stream. The input and output here are relative to the memory. Input Stream (input stream) refers to the data flowing into the memory from the outside (disk, network), and Output Stream refers to the data flowing out from the memory to the outside (disk, network). When the program is running, the data resides in the memory and is executed by the ultra-fast computing core of the CPU. Where data exchange is involved (usually disk and network operations), an IO interface is required.

So who provides this IO interface? How are IO operations implemented in high-level programming languages?

The operating system is a general software program with the following general purposes:

  • Hardware driver

  • Process Management

  • Memory Management

  • Network Management

  • Security Management

  • I/O Management

The operating system shields the underlying hardware and provides a common interface upwards. Therefore, the ability to operate I/O is provided by the operating system. Every programming language encapsulates the low-level C interface provided by the operating system for developers to use, and Python is no exception.

2. File reading and writing implementation principles and operation steps


1. File reading and writing implementation principles

File reading and writing is a common IO operation. Based on the above description, it can be inferred that python should also encapsulate the underlying interface of the operating system and directly provide operation methods related to file reading and writing. In fact, this is true, and so are other languages ​​such as Java and PHP.

So what is the object we want to operate on? How do we get the object to be operated on?

Since the ability to operate I/O is provided by the operating system, and modern operating systems do not allow ordinary programs to directly operate the disk, you need to request the operating system to open an object when reading and writing files. (Often called file descriptor - file descriptor, referred to as fd), this is the file object we want to operate in the program.

Usually high-level programming languages ​​will provide a built-in function that opens a file object by receiving parameters such as "file path" and "file opening mode", and returns the file descriptor of the file object. So through this function we can get the file object to be operated on. This built-in function is called open() in Python and fopen() in PHP.

2. File reading and writing steps

The steps for reading and writing files in different programming languages ​​are generally the same. are the same, and are divided into the following steps:

1)打开文件,获取文件描述符2)操作文件描述符--读/写3)关闭文件
Copy after login

It’s just that the APIs for reading and writing files provided by different programming languages ​​are different. Some provide richer functions, while others are simpler.

It should be noted that:After the file read and write operation is completed, it should be closed in time. On the one hand, file objects occupy operating system resources; on the other hand, the operating system has limits on the number of file descriptors that can be opened at the same time. On the Linux operating system, you can pass ulimit -n to view this display quantity. If the file is not closed in time, data loss may also occur. Because when I write data to a file, the operating system does not write the data to the disk immediately. Instead, it first puts the data in the memory buffer and writes it to the disk asynchronously. When the close method is called, the operating system will ensure that all data that has not been written to the disk is written to the disk, otherwise the data may be lost.

3. File opening mode


Let’s first look at the function definitions for opening files in Python, PHP and C language

Python
# Python2open(name[, mode[, buffering]])# Python3open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Copy after login
Copy after login
PHP
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
Copy after login
C Language
int open(const char * pathname, int flags);
Copy after login

You will find that the parameters received by the built-in file opening methods of the above three programming languages ​​include not only a "file path name", but also A mode parameter (the flags parameter in the open function of C language has a similar effect). The mode parameter defines the mode when opening a file. Common file opening modes are: read-only, write-only, read-write, and append-only. There are some slight differences in the definition of file opening modes in different programming languages. Let's take a look at the file opening modes in Python.

##rRead only Open the file in write-only mode and point the file pointer to the file header; if the file does not exist, an error will be reportedwOpen the file in write-only mode and point the file pointer to the file header; if the file exists, clear its contents, if the file does not exist, create itaOpen the file in append-only writable mode and point the file pointer to the file Tail; if the file does not exist, create itr Added writable function based on rw Added readable function based on wa Added readable function based on abRead and write binary files (the default is t, indicating text), which needs to be used in conjunction with the above modes, such as ab, wb, ab, ab (POSIX systems, including Linux) Ignore this character)

思考1: r+、w+和a+都可以实现对文件的读写,那么他们有什么区别呢?

  • r+会覆盖当前文件指针所在位置的字符,如原来文件内容是"Hello,World",打开文件后写入"hi"则文件内容会变成"hillo, World"

  • w+与r+的不同是,w+在打开文件时就会先将文件内容清空,不知道它有什么用

  • a+与r+的不同是,a+只能写到文件末尾(无论当前文件指针在哪里)

思考2: 为什么要定义这些模式呢?为什么不能像我们用word打开一篇文档一样既可以读,又可以写,还可修改呢?

关于这个问题,我查了很多资料,也没找到很权威的说明。在跟同行朋友交流过程中,发现大家主要有两种观点:

  • 跟安全有关,有这种观点的大部分是做运维的朋友,他们认为这就像linux上的rwx(读、写、执行)权限。

  • 跟操作系统内核管理I/O的机制有关,有这种观点的大部分是做C开发的,特别是与内核相关的开发人员。为了提高读写速度,要写入磁盘的数据会先放进内存缓冲区,之后再回写。由于可能会同时打开很多文件,当要回写数据时,需要遍历以打开的文件判断是否需要回写。他们认为如果打开文件时指定了读写模式,那么需要回写时,只要去查找以“可写模式”打开的文件就可以了。

四、Python文件操作步骤示例


我们来读取这样一个文本文件:song.txt,该文件的字符编码为utf-8。

匆匆那年我们 究竟说了几遍 再见之后再拖延
可惜谁有没有 爱过不是一场 七情上面的雄辩
匆匆那年我们 一时匆忙撂下 难以承受的诺言
只有等别人兑现
Copy after login

1. 菜鸟实现(只是实现功能):

Python3实现:

# 第一步:(以只读模式)打开文件f = open('song.txt', 'r', encoding='utf-8')# 第二步:读取文件内容print(f.read())# 第三步:关闭文件f.close()
Copy after login

这里说下Python2的实现

# 第一步:(以只读模式)打开文件f = open('song.txt', 'r')# 第二步:读取文件内容print(f.read().decode('utf-8'))# 第三步:关闭文件f.close()
Copy after login

说明:
Python3中已经内置对Unicode的支持,字符串str已经是真正的Unicode字符串。也就是说Python3中的文件读取方法已经自动完成了解码处理,因此无需再手动进行解码,可以直接将读取的文件中的内容进行打印;Python2中的字符串str是字节串,读取文件得到的也是字节串,在打印之前应该手动将其解码成Unicode字符串。关于这部分的说明,可以参考之前这篇文章>

2. 中级实现

在实现基本功能的前提下,考虑一些可能的意外因素。因为文件读写时都有可能产生IO错误(IOError),一旦出错,后面包括f.close()在内的所有代码都不会执行了。因此我们要保证文件无论如何都能被关闭。那么可以用try...finally来实现,这实际上就是try...except..finally的简化版(我们只用Python3来进行示例演示):

f = ''try:
    f = open('song.txt', 'r', encoding='utf-8')    print(f.read())
    num = 10 / 0finally:    print('>>>>>>finally')    if f:
        f.close()
Copy after login

输出结果:

匆匆那年我们 究竟说了几遍 再见之后再拖延
可惜谁有没有 爱过不是一场 七情上面的雄辩
匆匆那年我们 一时匆忙撂下 难以承受的诺言
只有等别人兑现>>>>>>finally
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>ZeroDivisionError: division by zero</module></stdin>
Copy after login

输出结果说明,尽管with代码块中出现了异常,但是”>>>>>>finally“ 信息还是被打印了,说明finally代码块被执行,即文件关闭操作被执行。但是结果中错误信息还是被输出了,因此还是建议用一个完成的try...except...finally语句对异常信息进行捕获和处理。

3. 最佳实践

为了避免忘记或者为了避免每次都要手动关闭文件,我们可以使用with语句(一种语法糖,语法糖语句通常是为了简化某些操作而设计的)。with语句会在其代码块执行完毕之后自动关闭文件。因此我们可以这样来改写上面的程序:

with open('song.txt', 'r', encoding='utf-8') as f:    print(f.read())print(f.closed)
Copy after login

输出结果:

匆匆那年我们 究竟说了几遍 再见之后再拖延可惜谁有没有 爱过不是一场 七情上面的雄辩匆匆那年我们 一时匆忙撂下 难以承受的诺言只有等别人兑现True
Copy after login

是不是变得简介多了,代码结构也比较清晰了。with之后打印的f.closed属性值为True,说明文件确实被关闭了。

思考:
with语句会帮我们自动处理异常信息吗?

要回答这个问题就要提到“上下文管理器” 和 with语句的工作流程。

with语句不仅仅可以用于文件操作,它实际上是一个很通用的结构,允许使用所谓的上下文管理器(context manager)。上下文管理器是一种支持__enter__()和__exit__()这两个方法的对象。__enter__()方法不带任何参数,它在进入with语句块的时候被调用,该方法的返回值会被赋值给as关键字之后的变量。__exit__()方法带有3个参数:type(异常类型), value(异常信息), trace(异常栈),当with语句的代码块执行完毕或执行过程中因为异常而被终止都会调用__exit__()方法。正常退出时该方法的3个参数都为None,异常退出时该方法的3个参数会被分别赋值。如果__exit__()方法返回值(真值测试结果)为True则表示异常已经被处理,命令执行结果中就不会抛出异常信息了;反之,如果__exit__()方法返回值(真值测试结果)为False,则表示异常没有被处理并且会向外抛出该异常。

现在我们应该明白了,异常信息会不会被处理是由with后的语句返回对象的__exit__()方法决定的。文件可以被用作上下文管理器。它的__enter__方法返回文件对象本身,__exit__方法会关闭文件并返回None。我们看下file类中关于这两个方法的实现:

def __enter__(self): # real signature unknown; restored from __doc__
    """ __enter__() -> self. """
    return self    
def __exit__(self, *excinfo): # real signature unknown; restored from __doc__
    """ __exit__(*excinfo) -> None.  Closes the file. """
    pass
Copy after login

可见,file类的__exit__()方法的返回值为None,None的真值测试结果为False,因此用于文件读写的with语句代码块中的异常信息还是会被抛出来,需要我们自己去捕获并处理。

with open('song.txt', 'r', encoding='utf-8') as f:    print(f.read())    num = 10 / 0
Copy after login

输出结果:

匆匆那年我们 究竟说了几遍 再见之后再拖延
可惜谁有没有 爱过不是一场 七情上面的雄辩
匆匆那年我们 一时匆忙撂下 难以承受的诺言
只有等别人兑现
Traceback (most recent call last):  File "<stdin>", line 3, in <module>
ZeroDivisionError: division by zero</module></stdin>
Copy after login

注意: 上面所说的__exit__()方法返回值(真值测试结果)为True则表示异常已经被处理,指的是with代码块中出现的异常。它对于with关键字之后的代码中出现的异常是不起作用的,因为还没有进入上下文管理器就已经发生异常了。因此,无论如何,还是建议在必要的时候在with语句外面套上一层try...except来捕获和处理异常。

有关“上下文管理器”这个强大且高级的特性的更多信息,请参看Python参考手册中的上下文管理器部分。或者可以在Python库参考中查看上下文管理器和contextlib部分。

五、Python文件读取相关方法


我们知道,对文件的读取操作需要将文件中的数据加载到内存中,而上面所用到的read()方法会一次性把文件中所有的内容全部加载到内存中。这明显是不合理的,当遇到一个几个G的的文件时,必然会耗光机器的内存。这里我们来介绍下Python中读取文件的相关方法:

File Open Mode Description
##read()Read once All contents of the file, return a strread(size)Read up to the specified length of content each time, return a str; in Python2, size is specified Byte length, in Python3 size specifies the character lengthreadlines()Read all the contents of the file at once and return a list per linereadline()Read only one line at a time
Method Description
In addition, there are two more related to the file pointer position Method

MethodDescription##seek(n)tell()

下面来看下操作实例

1. 读取指定长度的内容

Python2
with open('song.txt', 'r') as f:    print(f.read(12).decode('utf-8'))
Copy after login

输出结果:

匆匆那年
Copy after login

结果说明:Python2中read(size)方法的size参数指定的要读取的字节数,而song.txt文件是UTF-8编码的内容,一个汉字占3个字节,因此12个字节刚好是4个汉字。

Python3
with open('song.txt', 'r', encoding='utf-8') as f:    print(f.read(12))
Copy after login

输出结果:

匆匆那年我们 究竟说
Copy after login

结果说明:Python3中read(size)方法的size参数指定的要读取的字符数,这与文件的字符编码无关,就是返回12个字符。

2. 读取文件中的一行内容

Python2
with open('song.txt', 'r', encoding='utf-8') as f:    print(f.readline())
Copy after login
Python3
with open('song.txt', 'r') as f:    print(f.readline().decode('utf-8'))
Copy after login

输出结果都一样:

匆匆那年我们 究竟说了几遍 再见之后再拖延
Copy after login

3. 遍历打印一个文件中的每一行

这里我们只以Python3来进行实例操作,Python2仅仅是需要在读取到内容后进行手动解码而已,上面已经有示例。

方式一:先一次性读取所有行到内存,然后再遍历打印

with open('song.txt', 'r', encoding='utf-8') as f:    for line in f.readlines():
        print(line)
Copy after login

输出结果:

匆匆那年我们 究竟说了几遍 再见之后再拖延

可惜谁有没有 爱过不是一场 七情上面的雄辩

匆匆那年我们 一时匆忙撂下 难以承受的诺言

只有等别人兑现
Copy after login
Copy after login

这种方式的缺点与read()方法是一样的,都是会消耗大量的内存空间。

方式二:通过迭代器一行一行的读取并打印

with open('song.txt', 'r', encoding='utf-8', newline='') as f:
    for line in f:
        print(line)
Copy after login

输出结果:

匆匆那年我们 究竟说了几遍 再见之后再拖延

可惜谁有没有 爱过不是一场 七情上面的雄辩

匆匆那年我们 一时匆忙撂下 难以承受的诺言

只有等别人兑现
Copy after login
Copy after login

另外,发现上面的输出结果中行与行之间多了一个空行。这是因为文件每一行的默认都有换行符,而print()方法也会输出换行,因此就多了一个空行。去掉空行也比较简单:可以用line.rstrip()去除字符串右边的换行符,也可以通过print(line, end='')避免print方法造成的换行。

file类的其他方法:

Move the file pointer to the specified byte position
Get the byte position of the current file pointer
方法 描述
flush() 刷新缓冲区数据,将缓冲区中的数据立刻写入文件
next() 返回文件下一行,这个方法也是file对象实例可以被当做迭代器使用的原因
truncate([size]) 截取文件中指定字节数的内容,并覆盖保存到文件中,如果不指定size参数则文件将被清空; Python2无返回值,Python3返回新文件的内容字节数
write(str) 将字符串写入文件,没有返回值
writelines(sequence) 向文件写入一个字符串或一个字符串列表,如果字符串列表中的元素需要换行要自己加入换行符
fileno() 返回一个整型的文件描述符,可以用于一些底层IO操作上(如,os模块的read方法)
isatty() 判断文件是否被连接到一个虚拟终端,是则返回True,否则返回False

六、文件读写与字符编码


前面已经写过一篇介绍Python中字符编码的相关文件> 里面花了很大的篇幅介绍Python中字符串与字符编码的关系以及转换过程。其中谈到过两个指定的字符编码的地方,及其作用:

How to read and write files in python

  • PyCharm等IDE开发工具指定的项目工程和文件的字符编码: 它的主要作用是告诉Pycharm等IDE开发工具保存文件时应该将字符转换为怎样的字节表示形式,以及打开并展示文件内容时应该以什么字符编码将字节码转换为人类可识别的字符。

  • Python源代码文件头部指定的字符编码,如*-* coding:utf-8 -*- 它的主要作用是告诉Python解释器当前python代码文件保存时所使用的字符编码,Python解释器在执行代码之前,需要先从磁盘读取该代码文件中的字节然后通过这里指定的字符编码将其解码为unicode字符。Python解释器执行Python代码的过程与IDE开发工具是没有什么关联性的。

那么这里为什么又要谈起字符编码的问题呢?

或者换个问法,既然从上面已经指定了字符编码,为什么对文件进行读写时还要指定字符编码呢?从前面的描述可以看出:上面两个地方指定的是Python代码文件的字符编码,是给Python解释器和Pycharm等程序软件用的;而被读写文件的字符编码与Python代码文件的字符编码没有必然联系,读写文件时指定的字符编码是给我们写的程序软件用的。这是不同的主体和过程,希望我说明白了。

读写文件时怎样指定字符编码呢?

上面解释了读写文件为什么要指定字符编码,这里要说下怎样指定字符编码(其实这里主要讨论是读取外部数据时的情形)。这个问题其实在上面的文件读取示例中已经使用过了,这里我们再详细的说一下。

首先,再次看一下Python2和Python3中open函数的定义:

# Python2open(name[, mode[, buffering]])# Python3open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Copy after login
Copy after login

可以看到,Python3的open函数中多了几个参数,其中包括一个encoding参数。是的,这个encoding就是用来指定被操作文件的字符编码的。

# 读操作with open('song.txt', 'r', encoding='utf-8') as f:
    print(f.read())# 写操作with open('song.txt', 'w', encoding='utf-8') as f:
    print(f.write('你好'))
Copy after login

那么Python2中怎样指定呢?Python2中的对文件的read和write操作都是字节,也就说Python2中文件的read相关方法读取的是字节串(如果包含中文字符,会发现len()方法的结果不等于读取到的字符个数,而是字节数)。如果我们要得到 正确的字符串,需要手动将读取到的结果decode(解码)为字符串;相反,要以特定的字符编码保存要写入的数据时,需要手动encode(编码)为字节串。这个encode()和decode()函数可以接收一个字符编码参数。Python3中read和write操作的都是字符串,实际上是Python解释器帮我们自动完成了写入时的encode(编码)和读取时的decode(解码)操作,因此我们只需要在打开文件(open函数)时指定字符编码就可以了。

# 读操作with open('song.txt', 'r') as f:
     print(f.read().decode('utf-8'))

# 写操作with open('song2.txt', 'w') as f:
    # f.write(u'你好'.encode('utf-8'))
    # f.write('你好'.decode('utf-8').encode('utf-8'))
    f.write('你好')
Copy after login
文件读写时有没有默认编码呢?

Python3中open函数的encoding参数显然是可以不指定的,这时候就会用一个“默认字符编码”。
看下Python3中open函数文档对encoding参数的说明:

encoding is the name of the encoding used to decode or encode thefile. This should only be used in text mode. The default encoding isplatform dependent, but any encoding supported by Python can be
passed.  See the codecs module for the list of supported encodings.
Copy after login

也就是说,encoding参数的默认值是与平台有关的,比如Window上默认字符编码为GBK,Linux上默认字符编码为UTF-8。

而对于Python2来说,在进行文件写操作时,字节会被直接保存;在进行文件读操作时,如果不手动进行来decode操作自然也就用不着默认字符编码了。但是这时候在不同的字符终端打印的时候,会用当前平台的字符编码自动将字节解码为字符,此时可能会出现乱码。如song.txt文件时UTF-8编码的,在windows(字符编码为GBK)的命令行终端进行如下操作就会出现乱码:

>>> with open('song.txt', 'r') as f:
...     print(f.read())
...
鍖嗗寙閭e勾鎴戜滑 绌剁珶璇翠簡鍑犻亶 鍐嶈涔嬪悗鍐嶆嫋寤?
鍙儨璋佹湁娌℃湁 鐖辫繃涓嶆槸涓€鍦?涓冩儏涓婇潰鐨勯泟杈?
鍖嗗寙閭e勾鎴戜滑 涓€鏃跺寙蹇欐拏涓?闅句互鎵垮彈鐨勮瑷€
鍙湁绛夊埆浜哄厬鐜
Copy after login

我们应该尽可能的获取被操作文件的字符编码,并明确指定encoding参数的值。

相关教程推荐:Python视频教程

The above is the detailed content of How to read and write files in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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!