您的位置:首页>科学 > Python--file 的with用法

Python--file 的with用法

2023-09-16 12:45

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

例如:

with www.webguidecorpuschristi.com('1.txt','rb') as f:print (www.webguidecorpuschristi.com())print (f.closed)
print (f.closed)

结果:

1111111
2222222
3333333
44444444
555555555
666666666
False
True

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

with www.webguidecorpuschristi.com('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 www.webguidecorpuschristi.com('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 www.webguidecorpuschristi.com('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