于 2020 年 1 月 7 日更新
我们可以使用文件处理来读写文件中的数据。
打开文件
在读/写之前,您首先需要打开文件。 打开文件的语法是。
f = open(filename, mode)
open()函数接受两个参数filename和mode。 filename是一个字符串参数,用于指定文件名及其路径,而mode也是一个字符串参数,用于指定文件的使用方式,即用于读取或写入。 f是文件处理器对象,也称为文件指针。
关闭文件
读/写完文件后,您需要使用close()这样的方法关闭文件,
f.close() # where f is a file pointer
打开文件的不同模式
| 模式 | 描述 |
|---|---|
"r" |
打开文件以只读 |
"w" |
打开文件进行写入。 如果文件已经存在,则在打开之前将清除其数据。 否则将创建新文件 |
"a" |
以附加模式打开文件,即将数据写入文件末尾 |
"wb" |
打开文件以二进制模式写入 |
"rb" |
打开文件以二进制模式读取 |
现在让我们看一些示例。
将数据写入文件
>>> f = open('myfile.txt', 'w') # open file for writing>>> f.write('this first line\n') # write a line to the file>>> f.write('this second line\n') # write one more line to the file>>> f.close() # close the file
注意:
write()方法不会像print()函数那样自动插入新行('\n'),需要显式添加'\n'来编写write()方法。
从文件读取数据
要从文件读回数据,您需要以下三种方法之一。
| 方法 | 描述 |
|---|---|
read([number]) |
从文件中返回指定数量的字符。 如果省略,它将读取文件的全部内容。 |
readline() |
返回文件的下一行。 |
readlines() |
读取所有行作为文件中的字符串列表 |
一次读取所有数据
>>> f = open('myfile.txt', 'r')>>> f.read() # read entire content of file at once"this first line\nthis second line\n">>> f.close()
将所有行读取为数组。
>>> f = open('myfile.txt', 'r')>>> f.readlines() # read entire content of file at once["this first line\n", "this second line\n"]>>> f.close()
只读一行。
>>> f = open('myfile.txt', 'r')>>> f.readline() # read the first line"this first line\n">>> f.close()
附加数据
要附加数据,您需要以'a'模式打开文件。
>>> f = open('myfile.txt', 'a')>>> f.write("this is third line\n")19>>> f.close()
使用for循环遍历数据
您可以使用文件指针遍历文件。
>>> f = open('myfile.txt', 'r')>>> for line in f:... print(line)...this first linethis second linethis is third line>>> f.close()
二进制读写
要执行二进制 I/O,您需要使用一个名为pickle的模块。 pickle模块允许您分别使用load和dump方法读取和写入数据。
写入二进制数据
>> import pickle>>> f = open('pick.dat', 'wb')>>> pickle.dump(11, f)>>> pickle.dump("this is a line", f)>>> pickle.dump([1, 2, 3, 4], f)>>> f.close()
读取二进制数据
>> import pickle>>> f = open('pick.dat', 'rb')>>> pickle.load(f)11>>> pickle.load(f)"this is a line">>> pickle.load(f)[1,2,3,4]>>> f.close()
如果没有更多数据要读取,则pickle.load()会引发EOFError或文件结尾错误。
在下一课中,我们将学习 python 中的类和对象。
