python exception and file handling mechanism

高洛峰
Release: 2017-02-28 16:33:13
Original
1385 people have browsed it

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: &#39;c&#39;
Copy after login

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
Copy after login

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
Copy after login

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"
Copy after login

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]])
Copy after login

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")
Copy after login

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
&#39;/music/_singles/kairo.mp3&#39;
>>> f.mode
&#39;rb&#39;
Copy after login

After opening the file. Read and write. For example:

>>> f.tell()
Copy after login
Copy after login

Query the current location.

0
>>> f.seek(0, 2)
Copy after login

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()
Copy after login
Copy after login

This will print the length of the file .

>>> f.seek(-128, 2)
>>> data = f.read(128)
Copy after login

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
Copy after login

Check whether the file is closed.

False
>>> f.close()
Copy after login

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
Copy after login

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(&#39;test.log&#39;, &#39;w&#39;)
Copy after login

'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(&#39;abc&#39;)
>>> f1.close()
>>> file(&#39;test.log&#39;).read()
Copy after login

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:
Copy after login

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
Copy after login

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
Copy after login

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")
Copy after login

这个join函数用来将一个或多个字符串构造成一个路径名.

&#39;c:\music\mahadeva.mp3&#39;
>>> os.path.expanduser("~")
Copy after login

expanduser函数用'~'作参数时. 返回当前用户根目录.
'c:\Documents and Settings\mpilgrim\My Documents'

>>> (filepath, filename) = os.path.split("c:\music\a.mp3")
Copy after login

split函数用来将一个路径名分成目录名和文件名. 它返回的是一个tuple. 用返回的tuple对(filepath, filename)赋值.

>>> filepath
&#39;c:\music&#39;
>>> filename
&#39;a.mp3&#39;
>>> (a, b) = os.path.splitext("a.mp3")
Copy after login

类似的. 这个splitext用来将一个全文件名分成 文件名 和 扩展名 两部分.

>>> a
&#39;a&#39;
>>> b
&#39;.mp3&#39;
Copy after login

列出目录用:

>>> os.listdir("c:\")
Copy after login

这个函数将返回一个字符串list. 包括所有的文件和文件夹的名字.

[&#39;boot.ini&#39;, &#39;CONFIG.SYS&#39;, &#39;AUTOEXEC.BAT&#39;, &#39;java&#39;, 等]
Copy after login

要判断一个字符串路径到底是一个文件还是一个文件夹. 用os.path模块中的 isfile() 或 isdir(). 如:

>>> [f for f in os.listdir("c:") if os.path.isdir(os.path.join("c:", f))]
Copy after login

这样就打印出c中所有文件夹名构成的list.

如果要在目录操作中使用通配符. 可以如下:

>>> import glob
Copy after login

要先导入 glob 模块

>>> glob.glob(&#39;c:\music\*.mp3&#39;)
Copy after login

则返回的list中包含了该目录下所有的 .mp3 后缀的文件名.

更多python异常和文件处理机制相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template