最新消息:

python read() readline() readlines() write() writelines()

python admin 3378浏览 0评论

open()成功执行后返回一个文件对象,以后所有对该文件的操作都可以通过这个“句柄”来进行,现在主要讨论下常用的输入以及输出操作。

输出:

read()方法用于直接读取字节到字符串中,可以接参数给定最多读取的字节数,如果没有给定,则文件读取到末尾。

readline()方法读取打开文件的一行(读取下个行结束符之前的所有字节),然后整行,包括行结束符,作为字符串返回。

readlines()方法读取所有行然后把它们作为一个字符串列表返回

eg:

文件/root/2.txt的内容如下,分别使用上面的三个方法来读取,注意区别:

read():

cat /root/2.txt

I’ll write this message for you
hehe,that’s will be ok.

>>>>fobj = open(‘/root/2.txt’)    ##默认已只读方式打开

>>>>a = fobj.read()

>>>>a

“I’ll write this message for younhehe,that’s will be ok.n”   ##直接读取字节到字符串中,包括了换行符

>>>> print a

I’ll write this message for you
hehe,that’s will be ok.

 

>>>>fobj.close()    ##关闭打开的文件

readline():

>>>> fobj = open(‘/root/2.txt’)

>>>>b  = fobj.readline()

>>>>b

“I’ll write this message for youn”    ##整行,包括行结束符,作为字符串返回

>>>>c = fobj.readline()

c

>>>>”hehe,that’s will be ok.n”      ##整行,包括行结束符,作为字符串返回

>>>>fobj.close()

readlines():

>>>>fobj = open(‘/root/2.txt’)

>>>> d = fobj.readlines()

>>>>d

["I'll write this message for youn", "hehe,that's will be ok.n"]    ##读取所有行然后把它们作为一个字符串列表返回

>>>>fobj.close()

输入:

write()方法和read()、readline()方法相反,将字符串写入到文件中。

和readlines()方法一样,writelines()方法是针对列表的操作。它接收一个字符串列表作为参数,将他们写入到文件中,换行符不会自动的加入,因此,需要显式的加入换行符。

eg:

write():

>>> >fobj = open(‘/root/3.txt’,’w’)      ###确保/root/3.txt没有存在,如果存在,则会首先清空,然后写入。
>>> >msg = ['write date','to 3.txt','finish']    ###这里没有显式的给出换行符
>>> >for m in msg:
…            fobj.write(m)
…
>>> >fobj.close()

cat /root/3.txt

write dateto 3.txtfinish

>>>>fobj = open(‘/root/3.txt’,’w’)    ###覆盖之前的数据

>>>>msg = ['write daten','to 3.txtn','finishn']     ###显式给出换行符

>>> >for m in msg:
…            fobj.write(m)
…
>>> >fobj.close()

cat /root/3.txt

write date
to 3.txt
finish

writelines():

>>>>fobj = open(‘/root/3.txt’,’w’)

>>>>msg = ['write daten','to 3.txtn','finishn']

>>>>fobj.writelines(msg)

>>>>fobj.close()

cat /root/3.txt

write date
to 3.txt
finish

转载请注明:爱开源 » python read() readline() readlines() write() writelines()

您必须 登录 才能发表评论!