This article mainly introduces python exceptions and file processing mechanisms, and analyzes in detail common statements, usage methods, and related precautions for handling Python exceptions, for more information about python exceptions and File Processing Mechanisms, see the examples in this article. We will share this with you for your reference. The details are as follows:
1. Exception handling
Python exception
Try
Except
Finally
And can be followed by else.
Raise
If the thrown exception is not processed, some Red information is displayed in Python IDE. when the real Python program is running, the program will be terminated.
We have seen several exceptions before:
If the key used in Dictionary does not exist, a KeyError exception is thrown. for example:
>>> d = {"a":1, "b":"abc"}>>> d["c"]Traceback (most recent call last): File "
", line 1, in
KeyError: 'c'
A value that does not exist in the search list. a ValueError exception is thrown. for example:
>>> li = [1,2]>>> li.index(3)Traceback (most recent call last): File "
", line 1, in
ValueError: list.index(x): x not in list
Corresponding. if the subscript is used to reference the elements in the list, if the subscript is out of bounds, an IndexError exception occurs. for example:
>>> li[2]Traceback (most recent call last): File "
", line 1, in
IndexError: list index out of range
If you call a method that does not exist, AttributeError is thrown.
Reference a non-existent variable. the NameError is thrown.
Data types are mixed without forced conversion. a TypeError exception is thrown.
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:
Open is a built-in function used to open a file and return a file object.
Try again t followed by the else statement. when the specified exception is not caught, execute the else statement.
When importing a module. if the module does not exist, an ImportError exception is thrown.
You can also define your own Exception classes. let it inherit the built-in Exception classes when defining them, and then use raise to throw exceptions.
2. work with file objects
As mentioned above, open can be used to open a file and return the object. its function declaration is as follows:
open(name[, mode[, buffering]])
There are three parameters (the last two are optional). They indicate the file name. open mode. buffer parameters. for example:
>>> f = open("/music/_singles/kairo.mp3", "rb")
The first parameter is set to "rb". it indicates that the file is opened in binary mode. If this parameter is set to default, the file is opened in text mode.
If it cannot be opened, open will cause an IOError.
Now you can use the name and mode attributes of the file object to query them. for example:
>>> f.name'/music/_singles/kairo.mp3'>>> f.mode'rb'
After opening the file, you can read and write it. 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 be 0. 1. 2. it indicates the beginning. current position. end.
If the location address is incorrect (for example, beyond the range), an IOError occurs.
Therefore, this statement positions the file pointer to the end of the file.
>>> f.tell()
This prints the length of the file.
>>> f.seek(-128, 2)>>> data = f.read(128)
Read the last 128 bytes of the file. the read data is returned as a string. when reading the data, the file pointer is also removed.
The read parameter indicates the maximum number of bytes read. this parameter can also be omitted. this parameter indicates that the object is always read at the end of the file.
If an error occurs during reading (such as a bad sector on the disk or the network is disconnected), an IOError occurs.
>>> f.closed
Check whether the file is closed.
False>>> f.close()
Close the file when it is no longer in use. you can close a closed file again (no exception occurs ).
>>> f.closedTrue
Otherwise, if you perform operations such as seek () on f, the ValueError exception is thrown.
The method for writing files is similar to reading files. However, it requires the file to be "written" and opened. for example:
>>> f1 = open('test.log', 'w')
'W' indicates that the write operation is enabled. in this way, the file will be created even if the file does not exist. If yes, 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 (). Therefore, 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 allow I to 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 as in other languages, you can use the following method:
>>> for i in range(len(li)) : print li[i]...123
Use for to traverse Dictionary as follows:
>>> d = {1:"abc", 2:"def"}>>> for k, v in d.items() : print "%d = %s" % (k, v)...1 = abc2 = def
The above print result and print "\ n ". join (["% d = % s" % (k, v) for k, v in d. same as items.
4. use sys. modules
In Python,. modules is a global dictionary object defined in the sys module.
Once we import a module, we can find it in sys. modules.
Each class has a built-in "class attribute": _ module _. its value is the name of the module that defines the class.
5. working with Directory
The module referenced by OS. path contains several operation files and directory functions. for example:
>>> import os>>> os.path.join("c:\music", "mahadeva.mp3")
This join function is used to construct one or more strings into a path name.
'c:\music\mahadeva.mp3'>>> os.path.expanduser("~")
Expanduser function '~ '. The root directory of the current user is returned.
'C: \ Documents and Settings \ mpilgrim \ My Documents Ents'
>>> (filepath, filename) = os.path.split("c:\music\a.mp3")
The split function is used to divide a path name into a directory name and a file name. it returns a tuple. assign values to (filepath, filename) using the returned tuple.
>>> filepath'c:\music'>>> filename'a.mp3'>>> (a, b) = os.path.splitext("a.mp3")
Similarly, this splitext is used to divide a full file name into two parts: file name and extension.
>>> a'a'>>> b'.mp3'
Used to list directories:
>>> os.listdir("c:\")
This function returns a string list, including the names of all files and folders.
['Boot. ini ', 'config. SYS', 'autoexec. bat', 'Java', etc.]
Determine whether a string path is a file or a folder. use isfile () or isdir () in the OS. path module. for example:
>>> [f for f in os.listdir("c:") if os.path.isdir(os.path.join("c:", f))]
In this way, the list consisting of all folder names in c is printed.
If you want to use wildcards in directory operations, you can:
>>> import glob
Import glob module first
>>> glob.glob('c:\music\*.mp3')
The returned list contains all. mp3 file names under the Directory.