您的位置:首页 > 编程语言 > Python开发

【Python 2】文件与异常

2015-12-16 16:50 871 查看

文件与异常

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python