第10章 文件和异常

10.1 从文件中读取数据

10.1.1 读取整个文件

  • 只需调用open(),无需调用close(),python会在合适的时候自动将其关闭
with open('文件名、后缀名') as file_object:
     contents=file_object.read()

10.1.2 文件路径

  • linux中绝对路径用/表示
  • windows中绝对路径用\表示

10.1.3 逐行读取

with open('文件名、后缀名') as file_object:
    for line in file_object:
	   print(line.rstrip())

10.1.4 创建一个包含文件各行内容的列表

with open('文件名.后缀名') as file_object:
    lines=file_object.readlines()

for line in lines:
   print(line.rstrip())

10.1.5 使用文件的内容

  • 读取文本文件时,python将其中的所有文本都解读为字符串
  • 如果想做数值使用,就必须使用函数int()将其转换为整数,或使用函数float将其转换为浮点数

10.1.6 包含一百万位的大型文件中的一部分

  • 利用列表提取元素的方式

10.2 写入文件

文件常用模式:

  • 读取模式 'r'
  • 写入模式 'w'
  • 附加模式 'a'
  • 能够读取和写入文件的模式 'r+'

10.2.1 写入空文件

with open('文件名.后缀名','w') as file_object:
   file_object.write()

10.3 存储数据

  • json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象
  • json.load():读取数据
with open(filename,'w') as f_obj:
     json.dump(username,f_obj)

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

print(username)
posted @ 2022-11-23 19:25  Trouvaille_fighting  阅读(21)  评论(0)    收藏  举报