The examples in this article describe python exceptions and file processing mechanisms. Share it with everyone for your reference, the details are as follows:
1 Exception handling
Use exceptions in Python
try
except
finally
to handle. And except can also be followed by else.
To raise an exception, use raise
If the thrown exception is not handled. Some red information is displayed in the Python IDE. When the real Python program is running, it will cause the program to terminate.
We have seen several exceptions before:
If the key used in the Dictionary does not exist, KeyError will be raised Exception. For example:
>>> d = {"a":1, "b":"abc"} >>> d["c"] Traceback (most recent call last): File "<interactive input>", line 1, in <module> KeyError: 'c'
A value that does not exist in the search list will raise a ValueError exception. For example:
>>> li = [1,2] >>> li.index(3) Traceback (most recent call last): File "<interactive input>", line 1, in <module> ValueError: list.index(x): x not in list
corresponds. If you use a subscript to refer to an element in the list. If the subscript is out of bounds, an IndexError exception will be generated. For example:
>>> li[2] Traceback (most recent call last): File "<interactive input>", line 1, in <module> IndexError: list index out of range
Call a method that does not exist. An AttributeError exception will be raised.
Reference to a non-existent variable. A NameError exception will be raised.
Mixing data types without forced conversion will raise a TypeError exception.
IOError caused by file operation error. For example:
try: fsock = open("/notthere") except IOError: print "The file dose not exits..." else: print "open the file." print "this line will always print"
Note that in the above code:
open is a built-in function. Used to open a file and return a file object.
try except can be followed by an else statement. When the specified exception is not caught, the else statement is executed.
When importing a module. If the module does not exist . Will raise an ImportError exception.
You can also define your own exception class. When defining, let it inherit the built-in Exception class. Then use raise to throw an exception when you need to throw it.
2 Working with file objects
As mentioned earlier, open can be used to open files and return file objects. Its function declaration is as follows:
open(name[, mode[, buffering]])
has 3 parameters (the last two are optional). They respectively represent the file name. Opening method. Buffer parameters. For example:
>>> f = open("/music/_singles/kairo.mp3", "rb")
The second parameter is specified as "rb". It means opening the file for binary reading. If this parameter is defaulted, it means opening it in text mode.
If it cannot be opened, open will raise an IOError. Exception.
Now you can use the name attribute and mode attribute of the file object to query them. For example:
>>> f.name '/music/_singles/kairo.mp3' >>> f.mode 'rb'
After opening the file. Read and write. For example:
>>> f.tell()
Query the current location.
0 >>> f.seek(0, 2)
Location File pointer. The first parameter is the offset value. The second parameter can take three values: 0. 1. 2. They represent the beginning, the current position, and the end respectively.
If the located address is incorrect (for example, it exceeds range), an IOError exception is raised.
So this statement positions the file pointer to the end of the file.
>>> f.tell()
This will print the length of the file .
>>> f.seek(-128, 2) >>> data = f.read(128)
Read the last 128 bytes of the file. And return the read data as a string. When reading the data, the file is also moved backward. Pointer.
The parameter of read indicates the maximum number of bytes to be read. This parameter can also be omitted. It means reading to the end of the file.
If an error occurs during reading (such as on the disk There are bad sectors or the network is disconnected). Raise an IOError exception.
>>> f.closed
Check whether the file is closed.
False >>> f.close()
The file should be closed when no longer in use. An already closed file can be closed again (no exception will occur).
>>> f.closed True
After closing, if you perform seek() and other operations on f, a ValueError exception will be raised.
The method of writing a file is similar to reading. However, it requires that the file is opened for "writing". For example:
>>> f1 = open('test.log', 'w')
'w' means open for writing. In this way, even if the file does not exist, it will be created. If it exists, the existing file will be overwritten.
>>> f1.write('abc') >>> f1.close() >>> file('test.log').read()
Opening a file with file() is the same as opening it with open(). So print:
'abc'
3 for Loop
In Python. for is used to iterate over a List. For example:
>>> li = [1, 2, 3] >>> for i in li:
This will let i receives the values of the elements in li in turn.
... print i
...
1
2
3
This output is the same as print " \n".joni(li) is the same.
If you want to use for for counting like in other languages, you can use the following method:
>>> for i in range(len(li)) : print li[i] ... 1 2 3
Use for to traverse Dictionary. As follows:
>>> d = {1:"abc", 2:"def"} >>> for k, v in d.items() : print "%d = %s" % (k, v) ... 1 = abc 2 = def
The above print result and print "\n".join(["%d = %s " % (k, v) for k, v in d.items()]) Same.
#4 Use sys.modules
in Python. modules are A global dictionary object defined in the sys module.
Once we import a module, we can find it in sys.modules.
Every class has a built-in "class Attribute": __module__. Its value is the name of the module that defines this class.
5 Working with Directory
There are several modules referenced by os.path Functions for operating files and directories. For example:
>>> import os >>> os.path.join("c:\music", "mahadeva.mp3")
这个join函数用来将一个或多个字符串构造成一个路径名.
'c:\music\mahadeva.mp3' >>> os.path.expanduser("~")
expanduser函数用'~'作参数时. 返回当前用户根目录.
'c:\Documents and Settings\mpilgrim\My Documents'
>>> (filepath, filename) = os.path.split("c:\music\a.mp3")
split函数用来将一个路径名分成目录名和文件名. 它返回的是一个tuple. 用返回的tuple对(filepath, filename)赋值.
>>> filepath 'c:\music' >>> filename 'a.mp3' >>> (a, b) = os.path.splitext("a.mp3")
类似的. 这个splitext用来将一个全文件名分成 文件名 和 扩展名 两部分.
>>> a 'a' >>> b '.mp3'
列出目录用:
>>> os.listdir("c:\")
这个函数将返回一个字符串list. 包括所有的文件和文件夹的名字.
['boot.ini', 'CONFIG.SYS', 'AUTOEXEC.BAT', 'java', 等]
要判断一个字符串路径到底是一个文件还是一个文件夹. 用os.path模块中的 isfile() 或 isdir(). 如:
>>> [f for f in os.listdir("c:") if os.path.isdir(os.path.join("c:", f))]
这样就打印出c中所有文件夹名构成的list.
如果要在目录操作中使用通配符. 可以如下:
>>> import glob
要先导入 glob 模块
>>> glob.glob('c:\music\*.mp3')
则返回的list中包含了该目录下所有的 .mp3 后缀的文件名.
更多python异常和文件处理机制相关文章请关注PHP中文网!