21fsdsd 发表于 2016-9-20 10:29:53

python read() readline() readlines() write() writelines()方法总结与区别

python read() readline() readlines() write() writelines()方法总结与区别输出:
read()方法用于直接读取字节到字符串中,可以接参数给定最多读取的字节数,如果没有给定,则文件读取到末尾。
readline()方法读取打开文件的一行(读取下个行结束符之前的所有字节),然后整行,包括行结束符,作为字符串返回。
readlines()方法读取所有行然后把它们作为一个字符串列表返回
文件/home/pjc/python/pjc.txt的内容如下,分别使用上面的三个方法来读取,注意区别:
who i am?   
I'm hehe
read()

1
2
3
4
5
6
7
>>> fobj = open('/home/pjc/python/pjc.txt')      #默认以只读方式打开   >>> a = fobj.read()
>>> a   
"who i am?\nI'm hehe\n"      #直接读取字节到字符串中,包括了换行符
>>> print a   
who i am?   
I'm hehe
>>>>fobj.close()




         #关闭打开的文件   

readline():

1
2
3
4
5
6
7
8
>>> fobj = open('/home/pjc/python/pjc.txt')   
>>> b = fobj.readline()   
>>> b         #读取整行,包括行结束符, 作为字符串返回   
'who i am?\n'   
>>> c = fobj.readline()   
>>> c         #读取整行,包括行结束符, 作为字符串返回 ,已经读到下一行了   
"I'm hehe\n"
>>> fobj.close()




readlines():
1
2
3
4
5
6
7
>>> fobj = open('/home/pjc/python/pjc.txt')   
>>> d = fobj.readlines()   
>>> d   
['who i am?\n', "I'm hehe\n"]   #读取
所有行
然后把它们作为一个字符串列表返回   
>>> fobj.close()





输入:write()方法和read()、readline()方法相反,将字符串写入到文件中。
和readlines()方法一样,writelines()方法是针对列表的操作。它接收一个字符串列表作为参数,将他们写入到文件中,换行符不会自动的加入,因此,需要显式的加入换行符。
write():
1
2
3
4
5
6
7
8
>>> fobj = open('/home/pjc/python/pjc.txt','w')   #确保pjc.txt没有存在,如果存在,则会首先清空,然后写入   
>>> msg = ['pengjc','shiqq','caoxy']          #没有显示的给出换行符   
>>> for m in msg:                              
...fobj.write(m)   
...   
>>> fobj.close()
# cat /home/pjc/python/pjc.txt   
pengjcshiqqcaoxy[iyunv@venus






1
2
3
4
5
6
7
8
9
10
>>> fobj = open('/home/pjc/python/pjc.txt','w')   #会覆盖之前的数据   
>>> msg = ['pengjc\n','shiqq\n','caoxy\n']       #显式给出换行符   
>>> for m in msg:   
...fobj.write(m)   
...   
>>> fobj.close()
# cat /home/pjc/python/pjc.txt   
pengjc   
shiqq   
caoxy




writelines():
1
2
3
4
5
6
7
8
>>> fobj = open('/home/pjc/python/pjc.txt','w')
>>> msg = ['pengjc\n','shiqq\n','caoxy\n']   
>>> fobj.writelines(msg)   
>>> fobj.close()
# cat /home/pjc/python/pjc.txt   
pengjc   
shiqq   
caoxy






页: [1]
查看完整版本: python read() readline() readlines() write() writelines()方法总结与区别