Python文件处理

纸上得来终觉浅,绝知此事要躬行。

Python文件处理

1. 文件打开

日常我们使用中,涉及最多就应该是对文件的处理了,其中文件的读取模式主要涉及到open函数,而该函数的参数又比较多,所以理解该函数才是文件处理的核心要点。

  • open:核心函数
open(file, mode='r',
    buffering=-1, encoding=None, errors=None,
    newline=None, closefd=True, opener=None)
# 使用open函数打开文件
try:
    f = open('note.txt', 'r')
    print(f.read())
finally:
    f.close()

1. 使用with文件上下文管理器
with open('note.txt', 'r') as f:
    print(f.read())
  • (1)mode:指定文件的读取模式
Character Meaning Description
r open for reading (default) 只读模式(默认)
w open for writing, truncating the file first 只写模式
x create a new file and open it for writing 创建新文件并打开写模式
a open for writing, appending to the end of the file if it exists 追加模式
b binary mode 二进制模式
t text mode (default) 文本模式(默认)
+ open a disk file for updating (reading and writing) 读写模式
U universal newline mode (deprecated) 已经弃用了
                     | r   r+   w   w+   a   a+   x   x+
---------------------|----------------------------------
allow read           | ✓   ✓        ✓        ✓        ✓
allow write          |     ✓    ✓   ✓    ✓   ✓    ✓   ✓
create new file      |          ✓   ✓    ✓   ✓    ✓   ✓
open existing file   | ✓   ✓    ✓   ✓    ✓   ✓
erase file contents  |          ✓   ✓
allow seek           |     ✓    ✓   ✓             ✓   ✓
position at start    | ✓   ✓    ✓   ✓             ✓   ✓
position at end      |                   ✓   ✓
In [1]: f = open('update_chis.sh', 'r')

In [2]: f
Out[2]: <_io.TextIOWrapper name='update_chis.sh' mode='r' encoding='UTF-8'>
  • (2)buffering:设置缓存大小
    • 文本模式下,不设置此参数,遇到换行刷新buffer
    • 二进制模式下,不设置此参数,根据操作系统自动判断buffer大小
    • 二进制模式下,设置此参数为0,关闭buffer
In [4]: f = open('update_chis.sh', buffering=1024)
  • (3)encoding:指定编码格式
    • encoding参数只在文本模式下生效
In [7]: f = open('update_chis.sh', encoding='utf-8')
  • (4)errors:指定无法解码时的处理模式
    • errors只在文本模式下生效
    • 参数strict表示严格模式,无法解码抛出异常
    • 参数ignore表示忽略模式,无法解码直接pass
In [20]: with open('xxx.txt', errors='ignore') as f:
    ...:     pass
    ...:
  • (5)newline:指定换行符
    • newline所指定换行符None、''、n、r、rn
In [21]: !echo "a.nb.nc." > note.txt

In [23]: cat note.txt
a.
b.
c.

In [24]: f = open('note.txt', newline='n')

In [25]: f.readlines()
Out[25]: ['a.n', 'b.n', 'c.n']

In [26]: f.close()

2. 文件对象

我们这里介绍一下,常用的文件操作函数。

  • close 函数
    • 关闭文件对象,并清空缓冲区
    • closed属性用来判断文件是否已经关闭
    • 在编程中最好使用with open方法,会自动关闭文件