温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

file文件操作

发布时间:2020-06-20 16:11:10 来源:网络 阅读:316 作者:io123 栏目:开发技术

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

输出:


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

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

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


eg:

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


1.read():


>>>> cat /root/10.txt

I'll write this message for you

hehe,that's will be ok.

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

>>>> a = fobj.read()

>>>> a

"I'll write this message for you\nhehe,that's will be ok.\n"   ##直接读取字节到字符串中,包括了换行符


>>>> print a

I'll write this message for you

hehe,that's will be ok.

 

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



2.readline():


>>>> fobj = open('/root/10.txt')

>>>> b  = fobj.readline()

>>>> b

"I'll write this message for you\n"    ##整行,包括行结束符,作为字符串返回

>>>> c = fobj.readline()

>>>> c

"hehe,that's will be ok.\n"      

##整行,包括行结束符,作为字符串返回

>>>> fobj.close()



3.readlines():


>>>> fobj = open('/root/10.txt')

>>>> d = fobj.readlines()

>>>> d

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

>>>> fobj.close()


4.xreadlines

xrange

Renames xrange() to range() and wraps existing range() calls with list.


xreadlines

Changes for x in file.xreadlines() to for x in file.

输入:


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

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

eg:

1.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 date\n','to 3.txt\n','finish\n']     ###显式给出换行符

>>>> for m in msg:

...    fobj.write(m)

...

>>>> fobj.close()

>>>> cat /root/3.txt

write date

to 3.txt

finish



2.writelines():


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

>>>>msg = ['write date\n','to 3.txt\n','finish\n']

>>>>fobj.writelines(msg)

>>>>fobj.close()

cat /root/3.txt

write date

to 3.txt

finish


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI