Python学习笔记
参考书目:《Python编程从入门到实践(第2版)》,[美] Eric Matthes,袁国忠译
十、文件和异常
1、从文件读取数据
1)读取文件
file_name= 'pi_digits.txt'
with open(file_name) as file_object: # 关键字with在不再需要访问文件后将其关闭
contents = file_object.read() # 读取内容并将其作为字符串赋给contents
print(contents)
3.1415926535
8979323846
2643383279
# 逐行读取
with open(file_name) as file_object:
for line in file_object:
print(line) # 使用line.rstrip()可以消去空行
3.1415926535
8979323846
2643383279
2)将文件的各行储存在列表中
with open(file_name) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
3.1415926535
8979323846
2643383279
print(lines)
[‘3.1415926535\n’, ’ 8979323846\n’, ’ 2643383279’]
3)用字符串储存文件内容
pi_string = ' '
for line in lines:
pi_string += line.strip() # 必须提前定义,否则会出错
print(pi_string,len(pi_string))
3.141592653589793238462643383279 32
2、写入文件
python只能将字符串写入文本文件,若要储存数值数据,须先使用str()将其转换为字符串
1)写入空文件
filename = 'programming.txt' # open()会自动创建文件
with open(filename,'w') as file_object: # 实参'w':写入模式。'r':读取模式。'a':附加模式。'r+':读写模式。省略则默认只读模式
file_object.write("I love programming.\n") # 若指定文件已经存在,以写入模式('w')打开时,python将清空该文件的内容
file_object.write("And you? \n")
with open(filename) as file_object:
contents = file_object.read()
print(contents)
I love programming.
And you?
2)附加到文件
with open(filename,'a') as file_object: # 附加模式('a')给文件添加内容,而不是覆盖
file_object.write("I also like it. \n")
with open(filename) as file_object:
contents = file_object.read()
print(contents)
I love programming.
And you?
I also like it.
3、异常
处理ZeroDivisionError异常
print(5/0)
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_19396\542782178.py in
1 # 处理ZeroDivisionError异常
----> 2 print(5/0)
ZeroDivisionError: division by zero
try: # try-except代码块
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
You can’t divide by zero!
try: # 存放可能引发异常的语句
answer = 5/2
except ZeroDivisionError:
print("You can't divide by zero!")
else: # else代码块,try成功执行时运行
print(answer)
2.5
pass语句可以让python什么都不做
4、储存数据
模块json能够将简单的python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。
json.dump()储存和json.load()读取,可以实现在程序之间共享数据。
JSON(JavaScrip Object Notation)格式最初是为JavaScript开发的,但随后被包括python在内的众多语言采用。
import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json' # 注意扩展名
with open(filename,'w') as f:
json.dump(numbers,f) # json.dump()用来储存
with open(filename) as f:
num = json.load(f) # # json.load()用来加载
print(num)
[2, 3, 5, 7, 11, 13]