Python–file 的with用法

  • Post author:
  • Post category:python


有时候在编码的时候老忘记关闭文件,现在我们给出一种自动关闭文件的方法,从而不需要我们手动每次写关闭函数。

例如:

with codecs.open('1.txt','rb') as f:
    print (f.read())
    print (f.closed)
print (f.closed)

结果:

1111111
2222222
3333333
44444444
555555555
666666666


False
True

2. 将文件下标与内容打印出来

with codecs.open('1.txt','rb') as ff:
    for line, value in enumerate(ff):
        print (line,value)
(0, '1111111\n')
(1, '2222222\n')
(2, '3333333\n')
(3, '44444444\n')
(4, '555555555\n')
(5, '666666666\n')

3. 打印文件行号与内容打印出来

with codecs.open('1.txt','rb') as ff:
    for line, value in enumerate(ff):
        print (line+1,value)
(1, '1111111\n')
(2, '2222222\n')
(3, '3333333\n')
(4, '44444444\n')
(5, '555555555\n')
(6, '666666666\n')

4. 打印指定行的值

with codecs.open('1.txt','rb') as ff:
    for line, value in enumerate(ff):
        if line==4-1:
            print value
44444444

另一种,方法:

import linecache
count= linecache.getline('1.txt',4)
print count
44444444



版权声明:本文为yanyangjie原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。