Python学习系列之异常和文件操作

来源:互联网 发布:无线mesh网络qos 编辑:程序博客网 时间:2024/06/09 00:35
异常和文件操作
同其他语言一样,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来完成文件的打开,返回文件对象,该对象有methodsattributes
    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]
  类似于dosunix下的通配符,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) ffor f in fileList]


 
  
  
 
 
 
 
   
 
 
原创粉丝点击