吾八哥博客

您现在的位置是:首页 > 码农手记 > Python > 正文

Python

记录学习Python里文本文件读写操作的方法

吾八哥2018-04-17Python3141

读写文本文件是工作中经常会遇到的一种需求,今天这里记录一下学习Python里读写文本文件的方法。

open方法

Python里打开和创建文本文件都是通过open方法来操作的,例如:

f = open('test.txt')
print(f.read())
f.close()

open方法的第二个参数mode是打开文件的模式,默认值为"r",根据Python源代码注释说明可知open方法的mode参数支持如下几种模式打开或者创建文本文件:

'r'       open for reading (default)
'w'       open for writing, truncating the file first
'x'       create a new file and open it for writing
'a'       open for writing, appending to the end of the file if it exists
'b'       binary mode
't'       text mode (default)
'+'       open a disk file for updating (reading and writing)
'U'       universal newline mode (deprecated)

文本文件读取

根据网络资料查询得知Python里读文本文件有如下几种方法:

read()将文本文件所有行读到一个字符串中,如果文件大于可用内存,不能使用这种处理。 
readline()是一行一行的读,支持行的跳过读取,由于每次读取一行,所以比readlines()效率低。
readlines()是将文本文件中所有行读到一个list中,文本文件每一行是list的一个元素。

具体demo代码如下:

def test_read():
    f = open('test.txt')
    print(f.read())
    f.close()

def test_readline():
    f = open('test.txt')
    while True:
        line = f.readline()
        if not line:
            break
        print(line)
    f.close()

def test_readlines():
    f = open('test.txt')
    lines = f.readlines()
    for line in lines:
        print(line)
    f.close()

文本文件写入

在要写入文本文件的时候,首先要将open的mode参数要指定为"w"可写模式。Python写文本文件有如下常用方法:

write()写入文本内容,写到内存
writelines()写入文本内容列表,写到内存
flush()将数据立即写入磁盘

具体例子如下:

def test_write():
    f = open('test.txt')
    f.write('www.XuePython.wang')
    f.close()
    
def test_writelines():
    f = open('test.txt')
    f.writelines(['学Python网', 'www.XuePython.wang'])
    f.close()

flush()方法这里就不写例子了,可以自行测试一下效果。

补充说明

补充一些以后在工作中可能需要用到的一些方法说明:

readable()判断文件是否可读
writable()判断文件是否可写
tell()获取当前文件的指针指向
seek()移动当前文件指针
truncate()清空文件内容
encoding文件的编码