Skip to content

Commit 4b2ad03

Browse files
authored
练习读取文件
1 parent 314c12d commit 4b2ad03

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Diff for: test28.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
'练习读取文件'
5+
6+
__author__ = 'sergiojune'
7+
8+
9+
# 默认编码方式是gbk,而编译器是utf-8,所以需要指定编码方式
10+
f = open('./test27.py', 'r', encoding='utf-8')
11+
# 读取文件全部内容,有一个参数为读取文件的大小
12+
# 当文件较小时可以这样读
13+
# txt = f. read()
14+
# print(txt)
15+
16+
# 还可以这样一行一行读
17+
print(f.readline())
18+
# 以一行行形式读全部内容
19+
for line in f.readlines():
20+
print(line)
21+
# 最后记得关闭文件
22+
f.close()
23+
24+
25+
# 当文件出现异常时,或许关闭不了文件,就需要捕捉异常
26+
try:
27+
f = open('./test26.py', 'r', encoding='utf-8')
28+
for x in f.readlines():
29+
print(x)
30+
except IOError as e:
31+
print(e)
32+
finally:
33+
# 最后一定关闭
34+
if f:
35+
f.close()
36+
37+
38+
# 如果每次都需要这样捕捉异常,就会很麻烦,python中可以用with语句块来处理
39+
with open('./test27.py', 'r', encoding='utf-8') as f:
40+
# 当离开这个语句块就会自动关闭,就不需要我们来关闭
41+
txt = f.read()
42+
print(txt)
43+
44+
45+
# 作业:请将本地一个文本文件读为一个str并打印出来
46+
# 上面的就是了,参考上面的

0 commit comments

Comments
 (0)