文件读取
按字节读取
➜ file cat read_test.txt
第1行
第2行
第3行
➜ file cat read_byte.py
with open("read_test.txt") as f:
print "read the first 3 bytes"
print 'data is: ' + f.read(3)
print 'file pointer is: ' + str(f.tell())
print
print "read the next 3 bytes"
print 'data is: ' + f.read(3)
print 'file pointer is: ' + str(f.tell())
print
f.seek(3)
print "seek file pointer and read 1 bytes"
print 'data is: ' + f.read(4)
print 'file pointer is: ' + str(f.tell())
➜ file python read_byte.py
read the first 3 bytes
data is: 第
file pointer is: 3
read the next 3 bytes
data is: 1�
file pointer is: 6
seek file pointer and read 1 bytes
data is: 1行
file pointer is: 7
第二次读取的中文不完整,所以出现了乱码
按行读取
➜ file cat read_test.txt
第1行
第2行
第3行
➜ file cat read_line.py
with open("read_test.txt") as f:
print "read the first line"
print 'data is: ' + f.readline().replace("\n", "")
print 'file pointer is: ' + str(f.tell())
print
print "read the rest lines"
for line in f.readlines():
print 'data is: ' + line.replace("\n", "")
print 'file pointer is: ' + str(f.tell())
➜ file python read_line.py
read the first line
data is: 第1行
file pointer is: 8
read the rest lines
data is: 第2行
file pointer is: 23
data is: 第3行
file pointer is: 23
读取不会自动去除结尾的换行符
文件遍历
➜ file cat read_test.txt
第1行
第2行
第3行
➜ file cat each_line.py
with open("read_test.txt") as f:
for line in f:
print line
➜ file python each_line.py
第1行
第2行
第3行
文件写入
按字节写入
➜ file cat write_test.txt
cat: write_test.txt: No such file or directory
➜ file cat write_byte.py
# encoding: utf-8
with open("write_test.txt", "wa") as f:
print "write the first 3 bytes"
f.write('你')
print "write the next 3 bytes"
f.write(u'好'.encode("utf-8"))
f.write("\n")
print "write unicode error"
f.write(u'好')
➜ file python write_byte.py
write the first 3 bytes
write the next 3 bytes
write unicode error
Traceback (most recent call last):
File "write_byte.py", line 12, in <module>
f.write(u'好')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u597d' in position 0: ordinal not in range(128)
➜ file cat write_test.txt
你好
文件写入默认使用
ASCII编码,所以报错了
按行写入
➜ file cat write_test.txt
cat: write_test.txt: No such file or directory
➜ file cat write_line.py
# encoding: utf-8
with open("write_test.txt", "wa") as f:
print "write the first line"
f.writelines("第1行" + "\n")
print "write the rest lines"
f.writelines(["第2行" + "\n", "第3行" + "\n"])
➜ file python write_line.py
write the first line
write the rest lines
➜ file cat write_test.txt
第1行
第2行
第3行
写入不会自动在结尾添加换行符
读写模式
open 函数的 mode 参数
| 模式 | 读写 | 说明 |
|---|---|---|
| r | 读 | 文件不存在会报错,文件指针在文件的开头 |
| r+ | 读写 | 文件不存在会报错,文件指针在文件的开头 |
| w | 写 | 清空已存在的文件或者文件不存在时自动创建,文件指针在文件的开头 |
| w+ | 读写 | 清空已存在的文件或者文件不存在时自动创建,文件指针在文件的开头 |
| a | 写 | 文件不存在时自动创建,文件指针在文件的末尾 |
| a+ | 读写 | 文件不存在时自动创建,文件指针在文件的末尾 |
缓冲模式
open 函数的 buffering 参数
| 模式 | 说明 |
|---|---|
| 0 | 无缓冲,有输入就写入磁盘 |
| 1 | 按行缓存,遇到换行符就写入磁盘 |
| n | 按大小缓冲,达到指定的大小就写入磁盘 |
n是大于1的数字