python文件与异常(2)
#写入文件 ‘’'file_name=‘C:\Users\Administrator\Desktop\python文件与异常\空文件.txt’#使用python创建一个名为空文件的txt文件 with open(file_name,‘w’) as file_object:#w表示写入 file_object.write(“你好!\n”)#注意w会将文件清空再写入 file_object.write(“你是谁?\n”)#默认再上一句后面接着写,可以使用 换行符进行换行

with open(file_name,‘a’) as file_object:#a是附加输入,不会清空原文件 file_object.write(“请告诉我你的名字:\n”)

#异常报错(可以先运行异常查看错误原因,然后写异常报错代码) try: print(5/0)#5除以0不满足运算条件,try中的代码如果无法运行就会执行except,若错误原因与except原因相同就会显示报错原因,并执行下面的语句 ZeroDivisionError:除数不能为0 except ZeroDivisionError: print(“除数不能为0”)’’’
#文本分隔 split()将一句话的单词用逗号分开,常用来计算文本字数
#存储数据 使用import导入json模块:json.dump()要存什么数据,存在哪里 #json.load()要读取什么数据
import json
numbers=[2,3,5,7,11,13]#需要储存的数据
filename=r’C:\Users\Administrator\Desktop\python文件与异常\number.json’ with open(filename,‘w’) as f:#写入打开文件赋值给f json.dump(numbers,f)#将number存再f中
with open(filename) as f: nambers=json.load(f)#读取储存的数据 print(numbers) 
#把用户输入的名字保存到username.json文件中 #向用户打招呼(从保存的文件中读取名字)
import json username=input(‘你的名字是?’) filename=r’C:\Users\Administrator\Desktop\python文件与异常\username.json’ with open(filename,‘a’)as k: json.dump(username,k) print(f"再见面时我会和你打招呼,{username}")
with open (filename)as k: user=json.load(k) print(f"欢迎回来,{user}") 
|