python-文件基本操作(一)
一、打开文件的方法:
fp=file("路径","模式")
fp=open("路径","模式")
注意:file()和open()基本相同,且最后要用close()关闭文件。 在python3中,已经没了file()这种方法
二、操作文件的模式:
打开文件有以下几种模式:
r :以只读方式打开文件
w:打开一个文件,只用于写。如果该文件已存在,则会覆盖,如果文件不存在,则会创建一个新文件
a:打开一个文件,用于追加。如果文件已存在,文件指针会放在文件末尾,如果文件不存在,则会创建一个新文件
三、写文件操作
#代码
fp=open('info','w')
fp.write('this is the first line')
fp.write('this is the second line')
fp.write('this is the third line')
f.close()
#文件内容结果
this is the first linethis is the second linethis is the third line
注:在写的过程中,内容不会自动换行,如想换行,需要在每个write()中加入"\n",如
#代码
fp=open('info','w')
fp.write('this is the first line\n')
fp.write('this is the second line\n')
fp.write('this is the third line\n')
f.close()
#文件内容结果
this is the first line
this is the second line
this is the third line
四、读文件操作
①一次性读取所有read()
>>> fp=open('info.log','r')
>>> print fp.read()
>>> fp.close()
this is the first line
this is the second line
this is the third line
②一次性读取所有,且把结果放入元组中readlines()
>>> fp=open('info.log','r')
>>> print fp.readlines()
>>> fp.close()
['this is the first line \n', 'this is the second line \n', 'this is the third line \n']
③读取一行readline()
>>> fp=open('info.log','r')
>>> print fp.readline()
>>> fp.close()
this is the first line
循环读取内容
>>> fp=file('info.log','r')
>>> for line in fp:
>>> print line
>>> fp.close()
this is the first line
this is the second line
this is the third line
#注:文件中的没一行带有"\n"换行,而使用print的时候,也会自动换行,因此输出结果中会有两次换行,如果想要达到只换行一次的效果,在print line后加入"," 如:
>>> print line,
this is the first line
this is the second line
this is the third line
五、追加文件内容
>>> fp=open('info.log','a')
>>> f.write('this is the append line\n')
>>> f.close()
this is the first line
this is the second line
this is the third line
this is the append line

浙公网安备 33010602011771号