01 使用open()函数打开文件夹

在读取一个文件的内容之前,需要先打开这个文件。在Python程序中可以通过内置函数open()来打开一个文件程序中,并用相关的方法读或写文件文件中的内容以供程序的处理和使用,同时可以将文件看作Python中的一种数据类型。

open(filename, mode='r', buffering=None, encoding=None, errors=None,

  newline=None, closefd=True, opener=None)

open: 打开

以读的方式:文本的方式, 二进制的方式

以写的方式:文本的方式,二进制的方式

写文件的时候:覆盖,追加(两种方式)

当使用上述函数open()打开一个文件后, 就会放回一个文件对象。上述格式中主要参数的具体说明如下所示:

filename:表示要打开的文件名。(路径+文件名)

mode:模式。

buffering:可选参数,缓冲区大小

encoding:文件编码类型。

文本文件才有可能需要编码,二进制文件不需要指定编码 否则会报出异常

errors:编码错误处理方式。

newline:控制通用换行符模式的行为。

closefd:控制在关闭文件时是否彻底关闭文件。

上述格式中,参数“mode”表示文件打开模式。在Python程序中,常用的文件打开模式如下表所示:

python文件处理模块 python 处理文件内容_爬虫

下图很好的总结了这几种模式:

python文件处理模块 python 处理文件内容_开发语言_02

#默认以文本读的方式打开

file_obj = open("file.txt", encoding="utf-8")

data = file_obj.read()

print(data)

file_obj.close()



file_obj = open("file.txt", "rt", encoding="utf-8")

data = file_obj.read()

print(data)

file_obj.close()



file_obj = open("file.txt", "w", encoding="utf-8")

data = file_obj.write("11111111111111111")

print(data)

file_obj.close()



file_obj = open("file2.txt", "w", encoding="utf-8")

data = file_obj.write("11111111111111111")

print(data)

file_obj.close()



file_obj = open("file2.txt", "a", encoding="utf-8")

data = file_obj.write("2222222222222")

print(data)

file_obj.close()



file_obj = open("file3.txt", "a+", encoding="utf-8")

file_obj.write("33333333333333333333333333")

file_obj.close()



file_obj = open("file.txt", encoding="utf-8")

data = file_obj.read()

file_obj.close()

二进制的方式(打开):

图片,音频,视频或者其他的非文本的文件

#打开”IO.png“文件,并以二进制的方式读出,  b不能单独使用(b前的r不能省略)

file_obj = open("IO.png", "rb")

data = file_obj.read()

print(data)

#关闭文件

file_obj.close()

#以二进制的方式写入文件”psb_copy.jpg“

file_obj = open("psb_copy.jpg", "wb")

file_obj.write(data)

#关闭文件

file_obj.close()

注意:“IO.png”文件中,以存入了一张照片。

02 文件的操作

以文本方式写入的文件, 无需指定编码以二进制方式写入文件,写入的内容要求为bytes,所以通过str.encode(‘utf-8’)来返回 bytes

文件写操作:write()方法

f.write("hello world")   #向目标文本文 件写入一行字符串                            

f.write("hello world".encode("utf-8"))  # 向目标二进制文件写入一行字符串



文件写操作:writelines()方法写入文件的字符串序列。

seq = ["hello world 1\n", "nihao wohao 2"] f.writelines( seq ) 7/15



文件读操作:read()方法从文件读取指定的字节数,如果未给定或为负则读取所有。

ret = f.read() #默认全部读出

ret = f.read(5) #读出指定长度字符



文件读操作:readline()方法可以读出一行数据

ret = f.readline() #读取一行

注意:有个很像的 readlines()方法 ret = f.readlines() #返回的是一个列表,且返回的是你读取的字符所在行的整个内容,但是当数据较大时,这样的用法会很占用内存。

03 使用File操作文件

File对象中的属性信息如下表所示:

python文件处理模块 python 处理文件内容_python文件处理模块_03

在Python程序中,对象File时通过内置函数实现对文件操作的,其中常用的内置函数如下:

python文件处理模块 python 处理文件内容_爬虫_04