学习python记录第五天

#文件的读写
text = ‘writing a text \n hello wolrd’
print(text)
my_file = open(‘file1.txt’,‘w’) #以写入的方式打开文件,如果不存在就会新建一个这样的文件
my_file.write(text)
my_file.close() #需要在写语句关闭文件

with open(‘file2.txt’, ‘w’)as f2: #清空文件,然后写入
f2.write(‘123123\nhahhah’)
with open(‘file2.txt’, ‘a’)as f2: #在文件最后追加内容
f2.write(text)
with open(‘file2.txt’, ‘r’)as f2: #以读取的方式打开文件
content = f2.read() #读取全部内容
print(content)

with open(‘file2.txt’,‘r’) as f2:
content1 = f2.readline() #读取一行的文件
print(content1)

with open(‘file2.txt’,‘r’) as f2:
content1 = f2.readlines() #读取所有行的文件然后打印成一行
print(content1)

filename = ‘file2.txt’
with open(filename) as f :
for line in f : #遍历文件并输出文件内容
print(line.rstrip()) #如果不加上 .rstrip 会存在两个空行 (文件本身就有了空行加上print也有空行)

#异常处理

file = open(‘hahha’,‘r+’) #r+的意思是先去读一个文件,如果能打开的话就可以写入

当执行这条语句的时候,会存在错误,报错
报错语句为:
Traceback (most recent call last):
File “D:/pycharm/lianxi/text.py”, line 1, in
file = open(‘hahha’,‘r+’) #r+的意思是先去读一个文件,如果能打开的话就可以写入
FileNotFoundError: [Errno 2] No such file or directory: 'hahha’

修改方案

try:
file = open(‘hahha.txt’, ‘r+’) #r+的意思是先去读一个文件,如果能打开的话就可以写入
except Exception as e: #将报错的信息保存在EXCEPTION中 这样就不会存在报错的情况
print(e)
response = input(‘do you want to create a file’) #查询到错误以后提供解决的方法
if response == ‘yes’:
file = open(‘hahha.txt’, ‘w’)
print(‘Has created a file’)
else:
pass
else: #没有出错的时候会执行这条语句
file.write(‘成功’) #在文件中写入成功
file.close()

json数据存储

import json
a_dict = {‘user_id’: ‘qbf’, ‘user_name’: ‘zhang’, “user_fit”: “pang”} #构建一个字典 这里发现似乎‘ ’ 和“ ” 是一样的效果
with open(‘example.json’, ’ w’) as f: #构建一个文件并命名为example.json
json.dump(a_dict, f) #将字典中的内容移到新建的example.json中
with open(‘example.json’) as f:
content = json.load(f) #打印出example.json中的内容
print(content)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值