python文件读写操作

最近的学习感悟:学一门知识最快的方法是先把知识点一个一个快速过一遍,然后在实践的过程中回忆这些知识点,并归纳总结这些知识点之间的联系,形成知识矩阵,这样知识就融会贯通了。

读写文件是较常见的IO操作。python中经常使用的读写文件方法有如下4种:

例如,文本text.txt,内容如下:

The first line
The second line
The third line

1 文件对象(迭代读)

文件句柄是可迭代对象,所以可以使用for进行迭代读操作。

#!/usr/bin/env python3
from collections.abc import Iterable

f = open('text.txt', 'r')
print(isinstance(f, Iterable))

num = 1
for con in f:
    print('col num is %d : %s'%(num, con), end='')
    num += 1

f.close()

脚本执行后的打印:

True
col num is 1 : The first line
col num is 2 : The second line
col num is 3 : The third line

2 read 与 write

这种方法与C语言类似,一般分为3步:

step1: 打开文件-->文件对象f = open(文件名, 访问模式)
step2: 读写文件-->调用文件对象f的read write方法
step3:关闭文件-->调用文件对象f的close()方法
#!/usr/bin/env python3
import os
f = open('text.txt', 'a+')
str1 = f.read() # 一次性读出文件所有内容,生成字符串。当然也可带size参数,读取指定字节数。
print(str1)

str_append = "The fourth line"
f.write('\n\n' + str_append) # 将字符串写入文件
f.close()

脚本执行后,text.txt的结果为:

The first line
The second line
The third line

The fourth line # 下面两行是新追加写入的

3 readline (切记没有writeline)

考虑一个特别大的文件,如果一次性读入,会导致内存吃不消,我们可以采用readline方式,每次只处理一行。

#!/usr/bin/env python3
f = open('text.txt', 'r')
while True:
    line = f.readline()
    if not line: # 为None跳出
        break
    print(line, end='')
f.close()

脚本执行后的打印:

The first line
The second line
The third line

4 readlines与 writelines

readlines每次一次读取文件中所有内容,与read不同的是:read读取的内容生成整个字符串,并且可以指定读取的字节数,而reaalines读到的内容是以行为单位的列表,只能读取文件所有内容。

#!/usr/bin/env python3
f = open('text.txt', 'r+') # 以读写方式打开文件
lines = f.readlines()
print(type(lines))  # 返回值为一个list
print(lines)

newlines=[]
for line in lines:
    print(line, end='')
    line = line.strip('\n') # 去掉每一行的换行符生成新的list
    newlines.append(line)
lines = f.writelines(newlines) # 重新写入新的list
f.close()

脚本执行后的打印:

<class 'list'>
['The first line\n', 'The second line\n', 'The third line']
The first line
The second line
The third line

写入新的list为,新生成的文本text.txt为:

The first line
The second line
The third lineThe first lineThe second lineThe third line

5 用with as优化open()

打开文件,当对文件的数据处理完之后,要对文件进行关闭处理,如果不将文件关闭会占用后台的内存,而且再次操作这个文件的时候它会打开失效。这种情况下,使用with 关键字就非常有用。

不需要 f.close()

with open('text.txt', 'r') as f:
    while True:
        line = f.readline()
        if not line:
            break
        print(line, end='')

脚本执行后的打印为:

The first line
The second line
The third line

归纳对比:

2 3 4
read 与 write readline (切记没有writeline) readlines与 writelines
读出指定大小的内容,默认为读取所有,返回值为str 只读一行 读出所有内容,返回值是是一个list
posted @ 2022-08-06 17:38  sureZ_ok  阅读(2461)  评论(0编辑  收藏  举报