第二节课:Python 操作文件

本贴最后更新于 1271 天前,其中的信息可能已经时移世易

学习目标:掌握python操作文件

python提供内置函数open()实现对文件的操作。

python对文本文件和二进制文件采用统一的操作步骤,和把大象放冰箱里一样分三步,"打开-操作-关闭。"

image.png

open函数

open(file, mode='r', encoding=None)

打开文件并返回对应的file object。如果该文件不能打开,则触发OSError

mode的取值:

字符 意义
'r' 文本读取(默认)
'w' 文本写入,并先清空文件(慎用),文件不存在则创建
'x' 文本写,排它性创建,如果文件已存在则失败
'a' 文本写,如果文件存在则在末尾追加,不存在则创建

mode组合的字符

字符 意义
'b' 二进制模式,例如:'rb'表示二进制读
't' 文本模式(默认),例如:rt一般省略t
'+' 读取与写入,例如:'r+' 表示同时读写

读文本文件

在当前目录下创建一个名为test.txt的文本文件,(注意编码方式)文件中写入下面的内容:

静夜思
床前明月光,疑是地上霜。
举头望明月,低头思故乡。

操作基本步骤

# 打开文件 mode=rt,t可以省略
fb = open('test.txt', 'r', encoding='utf-8')
# 读取
content = fb.read()
print(content)
# 关闭文件
fb.close()

上面这种操作经常会忘记关闭文件句柄,造成资源浪费,所以处理文件往往使用with语句进行上下文管理。

with open('test.txt', 'r', encoding='utf-8') as fb:
    content = fb.read()
    print(content)

with语句执行完毕会自动关闭文件句柄。

相对路径与绝对路径

进行文件处理时经常会碰到相对路径和绝对路径的问题。

绝对路径好理解,它指定了文件在电脑中的具体目录,以windows电脑为例:

d:\lemon\课件\python入门.md

相对路径一般是指相对当前脚本的路径,比如上面的案例中的test.txt因为和当前脚本在同一个文件夹下,所以可以直接使用test.txt作为文件名来操作。

也可显式的表达当前路径./test.txt,./表示当前目录。

../表示上级目录,同理../../表示上上级目录,依此类推。

那什么时候使用相对路径,什么时候使用绝对路径呢。

一般情况下项目本身的资源文件和脚本路径相对固定,为了不影响项目的移植性,必须使用相对路径。

如果需要读取操作系统中固定位置的系统文件一般使用绝对路径。

逐行读取

在读取文本文件时,经常需要按行读取,文件对象提供了多种方法进行按行读取。

从文件中读取一行;如果 f.readline() 返回一个空的字符串,则表示已经到达了文件末尾

with open('test.txt', 'r', encoding='utf-8') as fb:
    print(fb.readline())
    print(fb.readline())
    print(fb.readline())
    print(fb.readline())

以列表的形式返回文件中所有的行。

with open('test.txt', 'r', encoding='utf-8') as fb:
    content = fb.readlines()
    print(content)

要从文件中读取行,还可以循环遍历文件对象。这是内存高效,快速的,并简化代码:

# 5星推荐
with open('test.txt', 'r', encoding='utf-8') as fb:
    for line in fb:
        print(line)

读二进制文件

任何文件都可以以二进制读的方式打开,读取test.txt的二进制内容。

# mode=rb,不需要encoding参数
with open('test.txt', 'rb') as fb:
    content = fb.read()
    print(content)
# 也可以逐行读取,以\n换行符标志
with open('test.txt', 'rb') as fb:
    for line in fb:
        print(line)

写文本文件

清除写w

案例:将锄禾这首诗写入test.txt文件中

# mode=w 没有文件就创建,有就清除内容,小心使用
with open('test.txt', 'w', encoding='utf-8') as fb:
    fb.write('锄禾\n')
    fb.write('锄禾日当午,汗滴禾下土;\n')
    fb.write('谁知盘中餐,粒粒皆辛苦。\n')

运行后会发现之前写有静夜思的test.txt内容修改为锄禾,因为w模式会清除原文件内容,所以小心使用。

追加写 a

案例:将静夜思这首诗追加到test.txt文件中

# mode=a 追加到文件的最后
with open('test.txt', 'a', encoding='utf-8') as fb:
    fb.write('静夜思\n床前明月光,疑是地上霜;\n举头望明月,低头思故乡。\n')

排他写x

案例:在当前目录中创建文件test.txt,存在则不创建

# mode=x
try:
    with open('test.txt', 'x', encoding='utf-8') as fb:
        fb.write('')
except Exception as e:
    print(e)

[Errno 17] File exists: 'test.txt'

写二进制文件

在写模式后加b即是写二进制模式,这种模式下写入内容为字节数据。

例如:将爬到的图片二进制信息写入文件中。

import requests

url = 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1247698508,1430079989&fm=26&gp=0.jpg'

response = requests.get(url)

with open('校花.jpg', 'wb') as f:
    f.write(response.content)

读写文件

有时候需要能够同时读写文件,在模式后面加上+号即可给读模式添加写,给写模式添加读。

with open('test.txt', 'r+', encoding='utf-8') as f:
    # 读文件
    print(f.read())
    f.write('草\n离离原上草,一岁一枯荣;\n野火烧不尽,春风吹又生!\n')

锄禾
锄禾日当午,汗滴禾下土;
谁知盘中餐,粒粒皆辛苦。
静夜思
床前明月光,疑是地上霜;
举头望明月,低头思故乡。

案例:python处理解析csv文件

# 读取csv文件并解析为嵌套列表
data = []
with open('鸢尾.csv', 'r', encoding='gbk') as f:
    for line in f:
        # 去掉换行符
        line = line.strip()
        data.append(line.split(','))
data

[['id', '品种编号', '花瓣长', '花瓣宽', '花萼长', '花萼宽'],
['0', '0', '5.1', '3.5', '1.4', '0.2'],
['1', '0', '4.9', '3', '1.4', '0.2'],
['2', '0', '4.7', '3.2', '1.3', '0.2'],
['3', '0', '4.6', '3.1', '1.5', '0.2'],
['4', '0', '5', '3.6', '1.4', '0.2'],
['5', '0', '5.4', '3.9', '1.7', '0.4'],
['6', '0', '4.6', '3.4', '1.4', '0.3'],
['7', '0', '5', '3.4', '1.5', '0.2'],
['8', '0', '4.4', '2.9', '1.4', '0.2'],
['9', '0', '4.9', '3.1', '1.5', '0.1'],
['10', '0', '5.4', '3.7', '1.5', '0.2'],
['11', '0', '4.8', '3.4', '1.6', '0.2'],
['12', '0', '4.8', '3', '1.4', '0.1'],
['13', '0', '4.3', '3', '1.1', '0.1'],
['14', '0', '5.8', '4', '1.2', '0.2'],
['15', '0', '5.7', '4.4', '1.5', '0.4'],
['16', '0', '5.4', '3.9', '1.3', '0.4'],
['17', '0', '5.1', '3.5', '1.4', '0.3'],
['18', '0', '5.7', '3.8', '1.7', '0.3'],
['19', '0', '5.1', '3.8', '1.5', '0.3'],
['20', '0', '5.4', '3.4', '1.7', '0.2'],
['21', '0', '5.1', '3.7', '1.5', '0.4'],
['22', '0', '4.6', '3.6', '1', '0.2'],
['23', '0', '5.1', '3.3', '1.7', '0.5'],
['24', '0', '4.8', '3.4', '1.9', '0.2'],
['25', '0', '5', '3', '1.6', '0.2'],
['26', '0', '5', '3.4', '1.6', '0.4'],
['27', '0', '5.2', '3.5', '1.5', '0.2'],
['28', '0', '5.2', '3.4', '1.4', '0.2'],
['29', '0', '4.7', '3.2', '1.6', '0.2'],
['30', '0', '4.8', '3.1', '1.6', '0.2'],
['31', '0', '5.4', '3.4', '1.5', '0.4'],
['32', '0', '5.2', '4.1', '1.5', '0.1'],
['33', '0', '5.5', '4.2', '1.4', '0.2'],
['34', '0', '4.9', '3.1', '1.5', '0.1'],
['35', '0', '5', '3.2', '1.2', '0.2'],
['36', '0', '5.5', '3.5', '1.3', '0.2'],
['37', '0', '4.9', '3.1', '1.5', '0.1'],
['38', '0', '4.4', '3', '1.3', '0.2'],
['39', '0', '5.1', '3.4', '1.5', '0.2'],
['40', '0', '5', '3.5', '1.3', '0.3'],
['41', '0', '4.5', '2.3', '1.3', '0.3'],
['42', '0', '4.4', '3.2', '1.3', '0.2'],
['43', '0', '5', '3.5', '1.6', '0.6'],
['44', '0', '5.1', '3.8', '1.9', '0.4'],
['45', '0', '4.8', '3', '1.4', '0.3'],
['46', '0', '5.1', '3.8', '1.6', '0.2'],
['47', '0', '4.6', '3.2', '1.4', '0.2'],
['48', '0', '5.3', '3.7', '1.5', '0.2'],
['49', '0', '5', '3.3', '1.4', '0.2'],
['50', '1', '7', '3.2', '4.7', '1.4'],
['51', '1', '6.4', '3.2', '4.5', '1.5'],
['52', '1', '6.9', '3.1', '4.9', '1.5'],
['53', '1', '5.5', '2.3', '4', '1.3'],
['54', '1', '6.5', '2.8', '4.6', '1.5'],
['55', '1', '5.7', '2.8', '4.5', '1.3'],
['56', '1', '6.3', '3.3', '4.7', '1.6'],
['57', '1', '4.9', '2.4', '3.3', '1'],
['58', '1', '6.6', '2.9', '4.6', '1.3'],
['59', '1', '5.2', '2.7', '3.9', '1.4'],
['60', '1', '5', '2', '3.5', '1'],
['61', '1', '5.9', '3', '4.2', '1.5'],
['62', '1', '6', '2.2', '4', '1'],
['63', '1', '6.1', '2.9', '4.7', '1.4'],
['64', '1', '5.6', '2.9', '3.6', '1.3'],
['65', '1', '6.7', '3.1', '4.4', '1.4'],
['66', '1', '5.6', '3', '4.5', '1.5'],
['67', '1', '5.8', '2.7', '4.1', '1'],
['68', '1', '6.2', '2.2', '4.5', '1.5'],
['69', '1', '5.6', '2.5', '3.9', '1.1'],
['70', '1', '5.9', '3.2', '4.8', '1.8'],
['71', '1', '6.1', '2.8', '4', '1.3'],
['72', '1', '6.3', '2.5', '4.9', '1.5'],
['73', '1', '6.1', '2.8', '4.7', '1.2'],
['74', '1', '6.4', '2.9', '4.3', '1.3'],
['75', '1', '6.6', '3', '4.4', '1.4'],
['76', '1', '6.8', '2.8', '4.8', '1.4'],
['77', '1', '6.7', '3', '5', '1.7'],
['78', '1', '6', '2.9', '4.5', '1.5'],
['79', '1', '5.7', '2.6', '3.5', '1'],
['80', '1', '5.5', '2.4', '3.8', '1.1'],
['81', '1', '5.5', '2.4', '3.7', '1'],
['82', '1', '5.8', '2.7', '3.9', '1.2'],
['83', '1', '6', '2.7', '5.1', '1.6'],
['84', '1', '5.4', '3', '4.5', '1.5'],
['85', '1', '6', '3.4', '4.5', '1.6'],
['86', '1', '6.7', '3.1', '4.7', '1.5'],
['87', '1', '6.3', '2.3', '4.4', '1.3'],
['88', '1', '5.6', '3', '4.1', '1.3'],
['89', '1', '5.5', '2.5', '4', '1.3'],
['90', '1', '5.5', '2.6', '4.4', '1.2'],
['91', '1', '6.1', '3', '4.6', '1.4'],
['92', '1', '5.8', '2.6', '4', '1.2'],
['93', '1', '5', '2.3', '3.3', '1'],
['94', '1', '5.6', '2.7', '4.2', '1.3'],
['95', '1', '5.7', '3', '4.2', '1.2'],
['96', '1', '5.7', '2.9', '4.2', '1.3'],
['97', '1', '6.2', '2.9', '4.3', '1.3'],
['98', '1', '5.1', '2.5', '3', '1.1'],
['99', '1', '5.7', '2.8', '4.1', '1.3'],
['100', '2', '6.3', '3.3', '6', '2.5'],
['101', '2', '5.8', '2.7', '5.1', '1.9'],
['102', '2', '7.1', '3', '5.9', '2.1'],
['103', '2', '6.3', '2.9', '5.6', '1.8'],
['104', '2', '6.5', '3', '5.8', '2.2'],
['105', '2', '7.6', '3', '6.6', '2.1'],
['106', '2', '4.9', '2.5', '4.5', '1.7'],
['107', '2', '7.3', '2.9', '6.3', '1.8'],
['108', '2', '6.7', '2.5', '5.8', '1.8'],
['109', '2', '7.2', '3.6', '6.1', '2.5'],
['110', '2', '6.5', '3.2', '5.1', '2'],
['111', '2', '6.4', '2.7', '5.3', '1.9'],
['112', '2', '6.8', '3', '5.5', '2.1'],
['113', '2', '5.7', '2.5', '5', '2'],
['114', '2', '5.8', '2.8', '5.1', '2.4'],
['115', '2', '6.4', '3.2', '5.3', '2.3'],
['116', '2', '6.5', '3', '5.5', '1.8'],
['117', '2', '7.7', '3.8', '6.7', '2.2'],
['118', '2', '7.7', '2.6', '6.9', '2.3'],
['119', '2', '6', '2.2', '5', '1.5'],
['120', '2', '6.9', '3.2', '5.7', '2.3'],
['121', '2', '5.6', '2.8', '4.9', '2'],
['122', '2', '7.7', '2.8', '6.7', '2'],
['123', '2', '6.3', '2.7', '4.9', '1.8'],
['124', '2', '6.7', '3.3', '5.7', '2.1'],
['125', '2', '7.2', '3.2', '6', '1.8'],
['126', '2', '6.2', '2.8', '4.8', '1.8'],
['127', '2', '6.1', '3', '4.9', '1.8'],
['128', '2', '6.4', '2.8', '5.6', '2.1'],
['129', '2', '7.2', '3', '5.8', '1.6'],
['130', '2', '7.4', '2.8', '6.1', '1.9'],
['131', '2', '7.9', '3.8', '6.4', '2'],
['132', '2', '6.4', '2.8', '5.6', '2.2'],
['133', '2', '6.3', '2.8', '5.1', '1.5'],
['134', '2', '6.1', '2.6', '5.6', '1.4'],
['135', '2', '7.7', '3', '6.1', '2.3'],
['136', '2', '6.3', '3.4', '5.6', '2.4'],
['137', '2', '6.4', '3.1', '5.5', '1.8'],
['138', '2', '6', '3', '4.8', '1.8'],
['139', '2', '6.9', '3.1', '5.4', '2.1'],
['140', '2', '6.7', '3.1', '5.6', '2.4'],
['141', '2', '6.9', '3.1', '5.1', '2.3'],
['142', '2', '5.8', '2.7', '5.1', '1.9'],
['143', '2', '6.8', '3.2', '5.9', '2.3'],
['144', '2', '6.7', '3.3', '5.7', '2.5'],
['145', '2', '6.7', '3', '5.2', '2.3'],
['146', '2', '6.3', '2.5', '5', '1.9'],
['147', '2', '6.5', '3', '5.2', '2'],
['148', '2', '6.2', '3.4', '5.4', '2.3'],
['149', '2', '5.9', '3', '5.1', '1.8']]

# 将数据写为csv文件
with open('test.csv', 'w', encoding='utf-8') as f:
    for item in data:
        f.write(','.join(item) + '\n')

文件指针

open函数返回的文件对象使用文件指针来记录当前在文件中的位置。

read方法

在读模式下,使用文件对象的read方法可以读取文件的内容。它接收一个整数参数表示读取内容的大小,文本模式下表示字符数量,二进制模式下表示字节大小。

with open('test.txt', 'r', encoding='utf-8') as f:
    content = f.read(3)
    print(content)
content # '锄禾\n' 三个字符
with open('test.txt', 'rb') as f:
    content = f.read(3)
    print(content)
'锄'.encode('utf-8') # 三个字节

当以读的方式打开文件后文件指针指向文件开头,执行read操作之后,根据读取的数据大小指针移动到对应的位置。

tell方法

文件对象的tell方法返回整数,表示文件指针距离文件开头的字节数。

with open('test.txt', 'r', encoding='utf-8') as f:
    print(f.tell())
    content = f.read(3)
    print(content)
    print(f.tell())
content.encode('utf-8')

r模式打开文件后文件指针指向文件开头,执行read操作之后,根据读取的数据大小指针移动到对应的位置。

with open('test.txt', 'a', encoding='utf-8') as f:
    print(f.tell())

a模式打开文件后文件指针指向文件末尾。

seek方法

通过文件对象的seek方法可以移动文件句柄

seek方法接收两个参数:

注意文本模式下只允许从文件的开头进行偏移,也即只支持whence=0

with open('test.txt', 'r', encoding='utf-8') as f:
    print(f.read(3))
    # 跳转到文件开头
    f.seek(0)
    # 再读取第一个字
    print(f.read(1))

with open('test.txt', 'rb') as f:
    # 读取文件最后的10字节
    f.seek(-10,2)
    print(f.read())
2 操作
877649301 在 2020-10-26 15:57:34 更新了该帖
877649301 在 2020-08-27 17:35:40 更新了该帖
3 回帖
请输入回帖内容 ...
  • happy

    👍 效率很高啊

  • hopexuexia 1 评论

    image.png

    image.png

    image.png

    不错啊
    877649301
  • ArielTan 1 评论

    image.png

    因为编码选择gbk,会报错,所以调整成了utf-8

    image.png

    666
    877649301