共读Python编程-异常卡

2019-06-20  本文已影响0人  铺床高手

文件读取

读取整个文件

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents)

open() 打开读取文件
read()读入文件
with用于自动关闭文件流

文件路径

逐行读取

filename = 'pi_digits.txt'

with open(filename) as file_object:
     for line in file_object:
         print(line)

读取文件内容存储在列表中

lines = file_object.readlines()

写入文件

写入空文件

with open(filename, 'w') as file_object
    file_object.write("something")

open的第二个参数

写入多行

文本末尾加入\n换行符

附加到文件

指定模式实参为 a 追加模式

异常

使用try-except代码块

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

else代码块

try:
          answer = int(first_number) / int(second_number)
except ZeroDivisionError:
          print("You can't divide by 0!")
else:
          print(answer)

用于执行try代码块中代码成功执行后执行

存储数据

json

  1. 要存储的数据
  2. 用来存储的文件对象
  import json

  numbers = [2, 3, 5, 7, 11, 13]

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

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

  print(numbers)
上一篇 下一篇

猜你喜欢

热点阅读