https://blog.csdn.net/qq_41556318/article/details/84314565
try:
with open('data.txt') as f:
for each_line in f:
print(each_line)
except OSError as reason:
print('文件不存在'+str(reason))
注意,即便加上了with这个异常处理的except还是要和try进行并列的。
而且使用了with之后,for循环就要在with的下一级了
作业
0、else语句可以和while,for,if,try语句结合
1. 请问以下例子中,循环中的 break 语句会跳过 else 语句吗?
def showMaxFactor(num):
count = num // 2
while count > 1:
if num % count == 0:
print('%d最大的约数是%d' % (num, count))
break
count -= 1
else:
print('%d是素数!' % num)
num = int(input('请输入一个数:'))
showMaxFactor(num)
会跳过的,因为else是与while搭配的,只有在while正常执行完之后才会执行else语句的。也就说break跳出的是while而不仅仅是if。
count-1是和if进行并列的,如果没有进入if的话,就count-1
输入的数值要使用一下int
2. 请目测以下代码会打印什么内容?
try:
print('ABC')
except:
print('DEF')
else:
print('GHI')
finally:
print('JKL')
ABC GHI JKL
(else与异常处理搭配的时候就是没有问题就干吧
)
3. 使用什么语句可以使你不必再担心文件打开后却忘了关闭的尴尬?
使用with语句可以时刻监视文件是否关闭
try:
with open('data.txt,'w') as f:#加上with语句之后就会关注文件是否关闭了
for each_line in f:
print(each_line)
except OSError as reason:
print('出错啦:'+str(reason))
4. 使用 with 语句固然方便,但如果出现异常的话,文件还会自动正常关闭吗?
with语句会自动处理文件的打开和关闭,如果中途出现异常,会执行清理代码,然后确保文件自动关闭
with A() as a:
with B() as b:
suite
可以改写到一行中,这两个可以放到一行中
with A() as a,B() as b:
suite
使用with 语句
def file_compare(file1, file2):#定义的子函数
with open(file1) as f1, open(file2) as f2:#使用with打开文件
count = 0 # 统计行数
differ = [] # 统计不一样的数量
for line1 in f1:
line2 = f2.readline()
count += 1
if line1 != line2:
differ.append(count)
return differ
file1 = input('请输入需要比较的头一个文件名:')
file2 = input('请输入需要比较的另一个文件名:')
differ = file_compare(file1, file2)
if len(differ) == 0:
print('两个文件完全一样!')
else:
print('两个文件共有【%d】处不同:' % len(differ))
for each in differ:
print('第 %d 行不一样' % each)
注意如果在with后面是要打开多个文件,也是可以写道一行的。
with open('a.txt') as f1,open('b.txt') as f2: