前言
记性越来越不好了,每次用 python 读写文件都会和 golang 搞混,今天好好抽个时间单独来复习一下,记录下来。
常用的文件函数:open() read() readline() readlines() write() writelines()
open()
open() 函数用来打开文件,定义为:def open(name, mode=None, buffering=None)
mode 是文件的打开属性:r r+ w w+ a a+ rb rb+ wb wb+ ab ab+
buffering 参数是缓冲,默认没有缓冲,设置 1 表示有缓冲,一般不使用。
read() 、 readline() 和 readlines()
read()readline() readlines() 三个函数都是从文件中读数据. 。
只有文件的打开属性有读属性时才能正确读取文件,如 r r+等,而 w a 则无法读取数据。
准备一个文本文件:
|
1 2 3 4 |
line 1 : HelloWorld line 2 : HelloWorld line 3 : HelloWorld line 4 : HelloWorld |
read()
read()用来读取指定字节的数据, 也可以不指定默认读取所有数据。
|
1 2 3 4 5 6 7 8 9 10 11 |
fp = open("a.txt", "r") data = fp.read(10) # 打印最开始 10 个字节 line 1 : H print data content = fp.read() print content ##打印剩下所有的 ## elloWorld line 2 : HelloWorld line 3 : HelloWorld line 4 : HelloWorld |
readline()
readline() 用来读取一行数据
|
1 2 3 4 5 6 7 |
fp = open("a.txt", "r") while True: line = fp.readline() if line == "": break print line fp.close() |
由于每行后面有一个换行,
print 也会在每行后面加一个换行,所以每行之间有一个空行:
|
1 2 3 4 5 6 7 |
line 1 : HelloWorld line 2 : HelloWorld line 3 : HelloWorld line 4 : HelloWorld |
readlines()
readlines() 会读取所有数据并一行为单位放置到 list 中
|
1 2 3 4 5 6 |
fp = open("a.txt", "r") lines = fp.readlines() # 读取所有的行到列表 print type(lines) # <type "list"> for line in lines: print line # 这里打印的和上面代码打印的一样 fp.close() |
写文件
写文件的函数 write()和 writelines() ,写操作有两种模式:直接写和追加写。
直接写文件在打开文件时会把文件清空,文件指针指向文件开头。
追加模式不会清空文件,每次都会把数据加到文件末尾。每次追加数据之后指针都会指向文件末尾。
write()
|
1 2 3 4 |
write_data = "HelloWorld" fp = open("a.txt", "w") # w 和 w+模式打开文件都会先清空文件内容 fp.write(write_data) fp.close() |
文件中将会只有一行内容 HelloWorld:

writelines()
writelines() 用于写入多行数据
|
1 2 3 4 5 6 |
write_datas = ["HelloWorld ", "HelloWordpress "] fp = open("a.txt", "w") fp.writelines(write_datas) fp.close() |

以追加模式写
追加模式写文件不会清空数据
|
1 2 3 4 5 6 |
write_datas = ["HelloWorld2 ", "HelloWordpress2 "] fp = open("a.txt", "a") fp.writelines(write_datas) fp.close() |
a.txt 将在前面文本的基础上增加两行:

总结
python 文件读写操作相对简单,封装好的 readline()等函数用起来十分方便,要注意的地方是文件的读写模式不能弄错,还有同时进行读写操作时需要注意文件指针的位置。
读文件
读文件权限:r r+







评论