python编程:从入门到实践 第十章 文件和异常






with open('a.txt') as file:   #with 在不需要文件时将其关闭
    contents = file.read()
    print(contents.rstrip())    #当文件末尾出现空字符串时,显示出来就是一个空行


#每次读取一行

with open('a.txt') as file:
    for line in file:
        print(line.rstrip())     #会读取到文件末尾的换行符+print换行=存在空行
        #同样的rstrip消除

#读取一行 空格分隔一行
  #第一行 3.1415926535   897932   3846111 2643383279
flag=1
pistr=''


try:
    with open('a.txt') as file:
        for line in file:
            if flag:
                flag=0
                for num in line.split(' '):
                    pistr += num
            else:
                continue
except FileNotFoundError:
    #可使用 pass忽略错误
    msg="file not found!~~~~~~~~~~"
    print(msg)

print(pistr)


print("文件的写入 ")

writename='new.txt'


strinput=input("input your str!:")
with open(writename,'w') as file:    #文件不存在时自动创建
    file.write(strinput)

# 模式 a  附加        读取和写入 r+


print("异常 ")

try:
    print(5/0)
except ZeroDivisionError:
    print("fen mu bu neg weiling!")


#按q退出的除法计算器

while 1:
    fir=input("input zhe first num:")
    if fir == 'q' :
        break
    sec=input("input the second num:")
    if sec == 'q':
        break
    try:
        ans=int(fir)/int(sec)
    except ZeroDivisionError:
        print("sec==0???")
    else :
        print(ans)




















猜你喜欢

转载自blog.csdn.net/Big_Study_Father/article/details/89213557