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

来源:互联网 发布:淘宝网店计划书怎么写 编辑:程序博客网 时间:2024/05/21 19:21

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 / bexcept ZeroDivisionError:    print("you cant divide by zero!")else:    print("result:"+answer)

5.存储数据:

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

import jsonnumbers = [2,3,4,5]
filename = 'numbers.json'with open(filename,'w') as f_obj:    json.dump(numbers, f_obj)

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

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


原创粉丝点击