Python中读取文件的方式比较多,举例如下,先设置一个被读取的文件test.txt
,其内容如下所示:
I have no money. I have no job. I have no girl friend.
方式一:使用read()方法读取
f = open( "test.txt" ) lines = f.read() print lines, type(lines) f.close()
read()方法会一次性读取test.txt内的所有文本,返回成一个字符串类型对象。运行上述程序,输出如下:
I have no money. I have no job. I have no girl friend. <type 'str'>
方式二:使用readline()方法读取
f = open( "test.txt" ) line = f.readline() while line: print line, type(line) line = f.readline() f.close()
readline()方法会每一次读取一行为一个字符串对象,直到读取到不能读取为止。上述脚本运行结果如下:
I have no money. <type 'str'> I have no job. <type 'str'> I have no girl friend. <type 'str'>
方式三:使用readlines()方法读取
f = open( "test.txt" ) lines = f.readlines() print lines print type(lines) f.close()
readlines()方法是一次性将所有行读取成列表的形式返回。上述脚本运行结果如下:
['I have no money.\n', 'I have no job.\n', 'I have no girl friend.\n'] <type 'list'>
方式四:使用for语句读取
f = open( "test.txt" ) for line in f: print line, type(line) f.close()
直接使用for语句即可遍历指定文件的每一行,这种方式比readline()的方式来得简洁明了很多。上述脚本的运行结果如下:
I have no money. <type 'str'> I have no job. <type 'str'> I have no girl friend. <type 'str'>
方式五:使用with语句,可自动关闭文件
with open("test.txt") as f: for line in f: print line, type(line)
上面的四种方式,在结束时都需要对文件对象进行close操作;而使用with语句,则不再需要手动调用close方法,with语句会在结束后自动关闭文件对象。上述脚本的运行结果如下:
I have no money. <type 'str'> I have no job. <type 'str'> I have no girl friend. <type 'str'>
使用内置函数open来打开文件时,除了需要指定文件名,还可以通过第二个形参来指定打开文件的模式,常用的文件打开模式如下三种:
文件打开模式 | 说明 |
---|---|
r | f = open( "test.txt", "r" ) 读取(默认取值,即若不设置此参数,则默认为读取模式) |
w | f = open( "test.txt", "w" ) 写入(若没有此文件,则新建此文件写入内容;若此文件已经存在,则清空此文件内容重新写入新内容) |
a | f = open( "test.txt", "a" ) 追加(若没有此文件,则新建此文件写入内容;若此文件已经存在,则在已有文件末尾,追加写入新内容) |
以写入模式为例,如下所示:
f = open( "test.txt", "w" ) f.write( "I have no money." ) f.write( "I have no job." ) f.write( "I have no girl friend." ) f.close()
运行上述代码,即可生成test.txt文件如下:
I have no money. I have no job. I have no girl friend.
不管是读文件还是写文件,操作完毕后别忘了使用close方法关闭文件。