前言

记性越来越不好了,每次用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 表示有缓冲,一般不使用。

乱码问题的解决

UnicodeDecodeError: ''gbk'' codec can''t decode byte 0xac in position 372: illegal multibyte sequence

打开文件时加上编码标记即可:

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

read()、readline()和readlines()

read() readline() readlines() 三个函数都是从文件中读数据.。``

只有文件的打开属性有读属性时才能正确读取文件,如r r+ 等,而w a 则无法读取数据。

准备一个文本文件:

line 1 : HelloWorld
line 2 : HelloWorld
line 3 : HelloWorld
line 4 : HelloWorld

read()

read() 用来读取指定字节的数据, 也可以不指定默认读取所有数据。

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() 用来读取一行数据

fp = open("a.txt", "r")
while True:
    line = fp.readline()
    if line == "":
        break
    print line
fp.close()

由于每行后面有一个换行print 也会在每行后面加一个换行,所以每行之间有一个空行:

line 1 : HelloWorld
line 2 : HelloWorld
line 3 : HelloWorld
line 4 : HelloWorld

readlines()

readlines() 会读取所有数据并一行为单位放置到list

fp = open("a.txt", "r")
lines = fp.readlines() # 读取所有的行到列表
print type(lines)  # <type "list">
for line in lines:
    print line  # 这里打印的和上面代码打印的一样
fp.close()

写文件

写文件的函数write()writelines() ,写操作有两种模式:直接写和追加写。

直接写文件在打开文件时会把文件清空,文件指针指向文件开头。追加模式不会清空文件,每次都会把数据加到文件末尾。每次追加数据之后指针都会指向文件末尾。

write()

write_data = "HelloWorld"
fp = open("a.txt", "w")  # w和w+模式打开文件都会先清空文件内容
fp.write(write_data)
fp.close()

文件中将会只有一行内容HelloWorld

writelines()

writelines() 用于写入多行数据

write_datas = ["HelloWorld
", "HelloWordpress
"]
fp = open("a.txt", "w")
fp.writelines(write_datas)
fp.close()

以追加模式写

追加模式写文件不会清空数据

write_datas = ["HelloWorld2
", "HelloWordpress2
"]
fp = open("a.txt", "a") 
fp.writelines(write_datas)
fp.close()

a.txt 将在前面文本的基础上增加两行:

总结

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

读文件

读文件权限:r r+

最后修改:2017 年 09 月 28 日
如果觉得我的文章对你有用,请随意赞赏