python学习笔记(1)

学习笔记,放硬盘里可能哪天就丢了,还是放这吧。

1,异常

dive into python,6.1有这么一个例子:

>>> fsock = open("/notthere", "r")
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
IOError: [Errno 2] No such file or directory: '/notthere'
>>> try:
...     fsock = open("/notthere")
... except IOError:
...     print "The file does not exist, exiting gracefully"
... print "This line will always print"
The file does not exist, exiting gracefully
This line will always print

那么当异常不在except IOError里面呢?

try:
    fsock = open("/notthere")
except  ImportError:
    print "The file does not exist, exiting gracefully"
print "This line will always print"
C:\>test.py
Traceback (most recent call last):
  File "C:\1.py", line 2, in <module>
    fsock = open("/notthere")
IOError: [Errno 2] No such file or directory: '/notthere'

可以看到当异常匹配不上except时,还会由python处理。

所以,当对异常类型不了解或者懒得了解的话还是直接except后不要加类型的好:

try:
    fsock = open("/notthere")
except:
    print "The file does not exist, exiting gracefully"
print "This line will always print"
C:\>test.py
The file does not exist, exiting gracefully
This line will always print

2,

  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

else是当没有异常的时候执行,也就是正常的时候执行
finally是无论如何都会执行,下面的例子中是用了两个try和finally是为了确保关闭句柄。(如果放第一个try块外,虽然也会关闭句柄,但是open的时候也可能出错导致并没有句柄)

        try: 
            fsock = open(filename, "rb", 0)
            try:                           
                fsock.seek(-128, 2)
                tagdata = fsock.read(128)
            finally:
                fsock.close()              
            .
            .
            .
        except IOError:
            pass

3,文件打开模式,好奇怪,难道不能以rwb方式打开?:

>>> os.listdir(".")
['bin', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'Microsoft.VC90.
CRT.manifest', 'msvcr90.dll', 'NEWS.txt', 'pycairo-wininst.log', 'pygobject-wini
nst.log', 'pygtk-wininst.log', 'python.exe', 'python26.dll', 'pythonw.exe', 'REA
DME.txt', 'Removepycairo.exe', 'Removepygobject.exe', 'Removepygtk.exe', 'Script
s', 'share', 'tcl', 'Tools', 'w9xpopen.exe']
>>> test = open("NEWS.txt", "rwb")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] invalid mode ('rwb') or filename: 'NEWS.txt'
>>> test = open("NEWS.txt", "rb")
>>> test.close()
>>> test = open("NEWS.txt", "wb")
>>>

发表评论

邮箱地址不会被公开。 必填项已用*标注

*