python文件及异常

本文详细介绍了Python中文件的读写操作,包括使用split(), strip(), find()等函数处理文本,以及try, except, finally等语句进行异常处理。通过一个具体的例子,展示了如何读取并解析sketch.txt文件的内容,同时处理可能出现的IOError。

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

参与的函数
split()
strip()
find()
语法:
try :
excpt
finally

with
参与的模块
os

sketch.txt文件内容:

Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause)
Other Man: Yes it is!
Man: No it isn't!
(pause)
Man: It's just contradiction!
Other Man: No it isn't!
Man: It IS!
Other Man: It is NOT!
Man: You just contradicted me!
Other Man: No I didn't!
Man: You DID!
Other Man: No no no!
Man: You did just then!
Other Man: Nonsense!
Man: (exasperated) Oh, this is futile!!
(pause)
Other Man: No it isn't!
Man: Yes it is!

先查看当前工作目录

import os
os.getcwd()   #查看当前工作目录
os.chdir(r'C:\user\......') #定位到想要去的文件中(r的作用使\不被转义)
try:
	with open('sketch.txt') as date:  #打开文件赋给date,如果出现异常关闭文件
		for each_line in date:
			try:
				(role,line_spoken) = each_line.split(':',1) #碰见:号则分裂成列表,后面的1就只分裂一次,然后给前面的 role 和line_spoken
				if(role == 'Man'):
					line_spoken = line_spoken.strip()  #去掉字符串首位的空白字符和空格
					man.append(line_spoken)  #添加到列表中
				elif(role == 'Other Man'):
					line_spoken = line_spoken.strip()
					other.append(line_spoken)
			except ValueError:  主要是判断文件中不符合标准的字符串就直接跳过
				pass
except IOError as err:
	print('File error' + str(err))  出现异常则是文件

或者:
try:           #检测到打开文件异常就抛出 The。。。并且关闭文件
    date = open('sketch.txt')
    for each_line in date:
        try:	#和上面一样,中间出现出现不符合格式的就抛出异常
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            if (role == 'Man'):
                man.append(line_spoken)
            elif (role == 'Other Man'):
                other.append(line_spoken)
        except ValueError:
            pass
    date.close()   #做完了之后关闭文件
except IOError:
    print('The datefile is missing!')
finally:
    date.close()

这里展示with的作用

>>> try:
	with open('man_date.txt','w') as man_file,open('other_date.txt','w') as other_file:
		print(man,file = man_file)
		print(other,file = other.file)#这里打错了
except IOError as err:
	print('File error'+str(err))

	
Traceback (most recent call last):
  File "<pyshell#89>", line 4, in <module>
    print(other,file = other.file)#这里显示了
AttributeError: 'list' object has no attribute 'file'
抛出异常,因为other_file打错成了other.file,检查文件中发现 man_date中文件正常打印出来了
但是other_date中却是空的文件,这就显示出了with的作用,出现异常 man_file和other_file都被关闭了,但是man_file已经输出到文件了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值