python使用手册<7>终章——文件与异常

目录

1,从文件中读取数据

1.1打开文件open()

1.1.1打开不在同一目录下的文件

1.1.2编码设定

1.2关闭文件

1.2.1关键字with

1.2.2 close()

1.3读取文件

1.3.1逐行读取

2.写入文件

2.1写入空文件

2.2open实参 

3.异常

3.1 ZeroDivisionError异常

3.2静默异常

4.数据的存储

4.1json模块储存数据

json.dump()

json.load()


1,从文件中读取数据

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

注意将文件保存到同一目录下

1.1打开文件open()

打开文件的函数,使用文件必须先打开它、

括号内写出文件名

返回值为一个表示文件的对象

这里用as来赋值给一个变量

1.1.1打开不在同一目录下的文件

下一级文件打开方法

with open('text_files/filename.txt') as file_object:

 注意:虽然windows使用\来表示路径,但是并不影响

1.1.2编码设定

filename='text_files/filename.txt'
with open(filename,encoding='utf-8') as f:

1.2关闭文件

1.2.1关键字with

在不使用文件后将其关闭

1.2.2 close()

当然close也可以关闭文件,但是当程序因为bug而中断运行时,

数据肯也会因此受损丢失。

1.3读取文件

文件对象后面加.read

并将文件以字符串赋值给变量

值得注意的时read在末尾处会返回一个空行

可以用.rstrip()删除

1.3.1逐行读取

#...
    lines = file_object.readlines()
for line in lines:
    print(line.restrip())

2.写入文件

2.1写入空文件

这时候open()第二个位置需要加一个实参

with open('txttest.txt','w') as file_object:
    file_object.write('i love you')

2.2open实参 

'r'读取

'w'写入

'a'附加(和写入类似,但是不会覆盖原文本内容)

'r+'读写

3.异常

当程序出现异常时,py会创建一个异常对象,如果不做处理程序会自动停止

使用try-except来修复异常

3.1 ZeroDivisionError异常

print(5/0)

报错 

Traceback (most recent call last):
  File "E:\learning\python\coursework\error.py", line 1, in <module>
    print(5/0)
          ~^~
ZeroDivisionError: division by zero#异常对象

 solution

try:
    a=input()
    b=input()
    print(a/b)
except ZeroDivisionError:
    print('infinity ')
else:
    print(answer)

将出现异常的代码块放到try:里面,并在except下面写下解决方案

3.2静默异常

try:
    a=input()
    b=input()
    print(a/b)
except ZeroDivisionError:
    pass
else:
    print(answer)

pass关键字:什么也不做

4.数据的存储

4.1json模块储存数据

JSON(JavaScript Object Notation)

json.dump()

#两个实参,第一个是储存数据,第二个是文件对象
import json
numbers=[1,2,3]
filename='a.json'
with open(filename,'w') as f:
    json.dump(numbers,f)

json.load()

import json
filename='a.json'
with open(filename) as f:
    json.load(f)

猜你喜欢

转载自blog.csdn.net/weixin_60787500/article/details/127783114