python学习之路七--文件与异常

1.文件的读取:

with open('my_file.txt') as my_file:
    contents = file_object.read()
    print(contents)
其中关注 with关键字在不需要访问文件后将自动关闭文件流

2.逐行读取:

with open('my_file.txt') as my_file:
    for line in my_file:
        print(line)


3.写入文件:

filename = "write_file"
with open(filename,'w') as my_file:
    my_file.write("I love you.")

其中open的第二个实参   指定读取模式('r')   写入模式('w')     附加模式('a')

4.异常:

最常见的事分母为0的时候,程序会报错  所以在避免这种错误时,python避免不必要的程序崩溃时,则通过try-except 来捕获异常

try:
    answer = a / b
except ZeroDivisionError:
    print("you cant divide by zero!")
else:
    print("result:"+answer)
 
 5.存储数据: 
 

使用json.dump()存储数据 :

import json

numbers = [2,3,4,5]

filename = 'numbers.json'
with open(filename,'w') as f_obj:
    json.dump(numbers, f_obj)

使用json.load()读取数据:

import json

filename = 'number.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)

print(numbers)


发布了49 篇原创文章 · 获赞 5 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/hehe0705/article/details/72520526
今日推荐