【Python 2】文件与异常

文件与异常

Python如何处理文件和异常。

使用open读文件

>>> import os
>>> os.getc
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    os.getc
AttributeError: module 'os' has no attribute 'getc'
>>> os.getcwd()
'D:\\Python35\\Lib\\idlelib'
>>> os.chdir('f:\Improve\Python\py')
>>> os.getcwd()
'f:\\Improve\\Python\\py'
>>> data=open('test.txt')
>>> print(data.readline)
<built-in method readline of _io.TextIOWrapper object at 0x000000F28983C630>
>>> print(data.readline(),end='')
Java
>>> print(data.readline(),end='')
C
>>> print(data.readline(),end='')
Python
>>> data.seek(0)
0
>>> print(data.readline(),end='')
Java
>>> for ii in data:
	print(ii,end='')

	
C
Python
Perl
>>> data.close()
>>> 

os.chdir():改变当前工作目录

open():读取文件

data.readline():读取一行数据

data.seek(0):移动游标到第一行

data.close():关闭文件资源


使用split函数,分割字符串

>>> data=open('test.txt')
>>> for dd in data:
	(name,desc)=dd.split(":")
	print(name,end='')
	print('--',end='')
	print(desc,end='')

	
乔丹--nba最牛逼的人
科比--投篮美如画
麦迪--干拔我最爱
>>> 


查看split帮助

>>> help(dd.split)
Help on built-in function split:

split(...) method of builtins.str instance
    S.split(sep=None, maxsplit=-1) -> list of strings
    
    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.

>>> 

>>> (a,b,c)='a:b:c:d'.split(':')
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    (a,b,c)='a:b:c:d'.split(':')
ValueError: too many values to unpack (expected 3)
>>> (a,b,c)='a:b:c:d'.split(':',3)
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    (a,b,c)='a:b:c:d'.split(':',3)
ValueError: too many values to unpack (expected 3)
>>> (a,b,c)='a:b:c:d'.split(':',4)
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    (a,b,c)='a:b:c:d'.split(':',4)
ValueError: too many values to unpack (expected 3)
>>> (a,b,c)='a:b:c:d'.split(':',2)
>>> print(a)
a
>>> print(c)
c:d
 >>> 

split()的第二个参数,代表用几个分隔符进行分隔

find方法

>>> str1='you are beautiful, lili'
>>> str1.find(':')
-1
>>> str1.find(',')
17
>>> if not str1.find(':')==-1:
    print('str1 contains :')
    
>>>

find,返回目标字符串索引位置

not,相当于Java的!

处理异常try/except机制

>>> data=open('test.txt')
>>> for aaa in data:
	try:
		(name,desc)=aaa.split(',')
		print(name,end='')
		print('--',end='')
		print(desc,end='')
	except:
		print('split occur error')

		
split occur error
split occur error
split occur error
>>> for aaa in data:
    try:
        (name,desc)=aaa.split(',')
        print(name,end='')
        print('--',end='')
        print(desc,end='')
    except:
        pass

    
>>> 

和Java的try-catch一样

pass可以跳过异常处理

>>> if os.path.exists('test1.txt'):
	data=open("test1.txt")
	data.close()
else:
	print('file not exist')

	
file not exist
>>>

else SyntaxError: invalid syntax

如果在else上面提示这个,绝对是缩进的问题

总结

异常产生运行时错误时,会出现一个traceback

traceback异常栈

open

readline

seek

close

split

help

find

not

try/except

pass


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值