异常和文件操作
同其他语言一样,
Python
也会对通过
try…except
来处理异常。例如:
try:
fsock = open(“/nothere”)
except IOError:
print “The file does not exist, exiting gracefully”
可见,当打开一个并不存在的文件时,会
raise
一个
IOError
异常。在标准库中,一个常用的异常是
ImportError
。如下例所示:
# Bind the name getpass to the appropriate function
try:
import termios, TERMIOS
except ImportError:
try:
import msvcrt
except ImportError:
try:
from EasyDialogs import AskPassword
except ImportError:
getpass = default_getpass
else:
getpass = AskPassword
else:
getpass = win_getpass
else:
getpass = unix_getpass
try…except
也可以和
else
配合使用,当没有异常发生时,会执行
else
语句。
接下来讨论文件操作:
Python
有内建函数
open
来完成文件的打开,返回文件对象,该对象有
methods
和
attributes
。
f = open(“/music/_single/kairo.mp3”, “rb”)
f
f.name
f.mode
f.tell()
f.seek(-128, 2)
tagData = f.read(128)
f.closed
f.close()
f.closed
调用
close()
函数后,
tell()
,
seek()
等都不能使用了。但是
name, mode
等都还存在。函数
write()
完成文件的写入。
logfile = open(‘test.log’, ‘w’)
logfile.write(‘test succeeded’)
logfile.close()
print file(‘test.log’).read()
如同其它语言一样,
Python
中也提供
for
循环,但是其使用频率没有其他语言那么高。
li = [‘a’, ‘b’, ‘e’]
for s in li:
print s
print “/n”.join(li)
li = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
for i in range(len(li)):
print li[i]
下面说说字典顺序的循环。
import os
for k, v in os.environ.items():
print “%s=%s” % (k, v)
print “/n”.join([“%s=%s” % (k, v) for k, v in os.environ.items()])
使用
sys.modules.
import sys
print “/n”.join(sys.modules.keys())
在
Python
中,每一个类都有一个内建属性
__module__
,表明该类是从属于那一个
modules
。可以使用
join()
构建绝对的路径。
import os
os.path.join(“c://music//ap//”, “mahadeva.mp3”)
os.path.expanduser(“~”)
os.path.split(“c://music//ap//mahadeva.mp3”)
(shortname, extension) = os.path.splitext(‘mahadeva.mp3’)
(shortname, extension) = os.path.splitext(“c://music//ap//mahadeva.mp3”)
列出一个路径下的所有文件。
os.listdir(“c://music//_singles//”)
dirname = “c://”
os.listdir(dirname)
如果遇到汉字,将显示国标码,例如“我的音乐”显示为
/xce/xd2/xb5/xc4/xd2/xf4/xc0/xd6.
如果需要仅仅显示路径则:
[f for f in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, f))]
def listDirectory(directory, fileExtList):
“get list of file info objects for files of particular extensions”
fileList = [os.path.normcase(f)
for f in os.listdir(directory)]
fileList = [os.path.join(directory, f)
for f in fileList
if os.path.splitext(f)[1] in fileExtList]
类似于
dos
和
unix
下的通配符,
Python
下可以用
module glob
来完成类似的功能。
os.listdir(“c://music//_singles//”)
import glob
glob.glob(“c://music//_singles//*.mp3”).
完整的
listDirectory
def ListDirectory(directory, fileExtList):
“get list of file info objects for files of particular extensions”
fileList = [os.path.normcase(f)
for f in os.listdir(directory)]
fileList = [os.path.join(directory, f)
for f in fileList
if os.path.splitext(f)[1] in fileExtList]
def getFileInfoClass(filename, module = sys.modules[FileInfo.__module__]):
“get file info class from filename extension”
subclass = “%sFileInfo” % os.path.splitext(filename)[1].upper()[1:]
return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
return [getFileInfoClass(f)
(
f
)
for f in fileList]