Python中的file(下)

首先,看下file有哪些方法,比较常用的用红色标标注出来。

f = codecs.open('3.txt', 'wb')
print(dir(f))
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', ' writelines ', 'xreadlines']


1、flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。

file = open('4.txt','wb')
file.write('abc')
file.flush()
file.close()

2、name返回文件的名称。

file = open('4.txt','wb')
file.write('abc')
file.flush()
file.close()
print '文件名为: ',file.name

3、write,writelines , readlines,readline,next 这三个结合着说

write()方法可以将任何字符串写入一个打开的文件。该方法不会在字符串的结尾添加换行符(“\n”)

writelines()作用: 用于向文件中写入一序列的字符串。这一序列字符串可以是迭代对象产生的,如字符串列表。换行需制定换行符\n

file = codecs.open('4.txt','wb')
file.write('aaaa\n')
file.writelines(['1111\n','2222\n','3333\n','4444\n'])
file.close()
aaaa
1111
2222
3333
4444

readlines()作用:用于读取所以行(直到结束符EOF),并返回列表。该列表可由for 语句处理。读取文件内容,文件内容的每一行都是一个字符串,最后返回一个list。

file = codecs.open('4.txt','rb')
print (file.readlines())
file.close()
['aaaa\n', '1111\n', '2222\n', '3333\n', '4444\n']

readline()作用:用于从文件中读取一行,返回一个字符串。包括“\n”.如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符。

file = codecs.open('4.txt','rb')
print (file.readline())
file.close()
aaaa

next()作用:读取文件的下一行内容,返回一个字符串。

file = codecs.open('4.txt','rb')
print (file.readline())
print (file.next())
print (file.next())
file.close()
aaaa
1111
2222

4、tell() 方法返回文件的当前位置,即文件指针当前位置。

file = codecs.open('4.txt','rb')
print (file.readlines())
print (file.tell())
file.close()
['aaaa\n', '1111\n', '2222\n', '3333\n', '4444\n']
25


5、file的with用法


http://python.jobbole.com/82494/  这篇文章写的很棒。

with codecs.open('4.txt','rb')  as file:
    print(file.readlines())
['aaaa\n', '1111\n', '2222\n', '3333\n', '4444\n']

with codecs.open('4.txt','rb')  as file: 

file = codecs.open('4.txt','rb')

表述的意思是一样的,只是with不需要在结尾close()




 









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr. Sun_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值