【python初识】文件存储与异常

本文介绍了Python中文件的基本操作,包括文件的打开与关闭、读取与写入、使用split和strip函数处理文本数据,以及如何进行异常处理确保程序稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件存储与异常

1、打开关闭文件

import os
if os.path.exists('sketch.txt'):
  the_file = open('sketch.txt')
  print(the_file.readline(),end=' '
  the_file.close()
else:
  print('the data is missing')

2、split函数

for each_line in data:
  if not each_line.find(':') == -1
    (role,line_spoken) = each_line.split(':',1) #分成两部分

3、异常处理

try:
  the_file = open('sketch.txt')
  print(the_file.readline(),end=' '
except IOError:
  print('the data is missing')
finally:
   the_file.close()

try:
  with open ('it.txt',"w") as data:
  print("aag",file = data)
except IOError as err:
  print("File error:" + str(err) )

4、strip函数

(role,line_spoken) = each_line.split(':',1)
line_spoken = line_spoken.srep() #从字符串去除不想要的字符

5、写入文件

out = open("data.out",'w')
print("NOR iii",file = out)
out.close()

6、保存文件

import pickle 

with open('mydata.pickle','wb') as msd
  pickle.dump([1,2,'t'],msd)

with open('mydata.pickle','rb') as mrd
  mlist = pickle.load(mrd)

print(mlist)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值