Home  >  Article  >  Backend Development  >  Detailed explanation of python exception and file processing mechanism

Detailed explanation of python exception and file processing mechanism

WBOY
WBOYOriginal
2016-08-04 08:55:381425browse

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

Exception use in Python
try
except
finally
to handle it. And except can also be followed by else .

To raise an exception, use raise

If the thrown exception is not handled, some red information will be displayed in the Python IDE. When the real Python program is running, it will cause the program to terminate.

We have seen several abnormalities before:

If the key used does not exist in the Dictionary, a KeyError exception will be raised. For example:

>>> d = {"a":1, "b":"abc"}
>>> d["c"]
Traceback (most recent call last): File "<interactive input>", line 1, in <module>
KeyError: 'c'

Search for a value that does not exist in the list. A ValueError exception will be raised. 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

Corresponding to

. 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 non-existent method. AttributeError exception will be raised.

References a variable that does not exist. Raises a NameError exception.

Mixing data types without coercion. Raises TypeError exception.

IOError caused by file operation error. Such as:

try:
  fsock = open("/notthere")
except IOError:
  print "The file dose not exits..."
else:
  print "open the file."
print "this line will always print"

Pay attention to the code above:

open is a built-in function. Used to open a file. And returns 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, an ImportError exception will be raised.

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 a file and return a file object. Its function declaration is as follows:

open(name[, mode[, buffering]])

There are 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 in binary reading mode. If this parameter is defaulted, it means opening it in text mode.

If it cannot be opened, open will raise an IOError exception.

You can now query file objects using their name attribute and mode attribute. For example:

>>> f.name
'/music/_singles/kairo.mp3'
>>> f.mode
'rb'

After opening the file, you can read and write. For example:

>>> f.tell()

Check current location.

0
>>> f.seek(0, 2)

Locate the file pointer. The first parameter is the offset value. The second one 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, exceeds the range), an IOError exception will be 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 pointer is also moved backward.

The parameter of read indicates the maximum number of bytes to be read. This parameter can also be omitted. It means reading until the end of the file.

If an error occurs during reading (such as bad sectors on the disk or the network is disconnected), an IOError exception will be raised.

>>> f.closed

Check if the file is closed.

False
>>> f.close()

Files should be closed when no longer in use. An already closed file can be closed again (no exception will occur).

>>> f.closed
True

If you perform seek() and other operations on f after closing, it will cause a ValueError exception.
The method of writing a file is similar to reading. However, it requires the file to be opened for "write". For example:

>>> f1 = open('test.log', 'w')

where '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 traverse a List. For example:

>>> li = [1, 2, 3]
>>> for i in li:

This will let i receive the values ​​of the elements in li in turn in the loop.

...print i
...
1
2
3

This output is the same as print "n".joni(li).
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 is the same as print "n".join(["%d = %s" % (k, v) for k, v in d.items()]).

4 Using sys.modules

In Python. modules is a global dictionary object defined in the sys module.

Once we import a module. It can be found in sys.modules.

Every class has a built-in "class attribute": __module__. Its value is the name of the module that defines the class.

5 Working with Directory

There are several functions for operating files and directories in the module referenced by os.path. 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相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn