python-06

  1. #!/usr/bin/env python
  2. #coding:utf8
  3. import os
  4. for tmpdir in ('/tmp', r'c:\temp'):
  5. if os.path.isdir(tmpdir):
  6. break
  7. else:
  8. print '没有这个目录'
  9. tmpdir = ''
  10. if tmpdir:
  11. os.chdir(tmpdir)
  12. cwd = os.getcwd()
  13. print '当前临时目录'
  14. print cwd
  15. print '创建目录'
  16. os.mkdir('example')
  17. os.chdir('example')
  18. cwd = os.getcwd()
  19. print '新目录'
  20. print cwd
  21. print '列出目录'
  22. print os.listdir(cwd)
  23. fobj = open('test', 'w')
  24. fobj.write('test1\n')
  25. fobj.write('test2\n')
  26. fobj.close()
  27. print '更新目录列表'
  28. print os.listdir(cwd)
  29. print '重新改名'
  30. os.rename('test', 'filetest.txt')
  31. print '重新列出目录'
  32. print os.listdir(cwd)
  33. path = os.path.join(cwd, os.listdir(cwd)[0])
  34. print '完整路径'
  35. print path
  36. print 'pathname, basename'
  37. print os.path.split(path)
  38. print '文件名, 扩展名'
  39. os.path.splitext(os.path.basename(path))
  40. print '显示文件内容'
  41. fobj = open(path)
  42. for eachline in fobj:
  43. print eachline,
  44. fobj.close()
  45. print '删除test文件'
  46. os.remove(path)
  47. print '更新目录'
  48. print os.listdir(cwd)
  49. os.chdir(os.pardir)
  50. print '删除test目录'
  51. os.rmdir('example')
  52. print 'END!'

 异常
处理方法一:
  1. #!/usr/bin/env python
  2. import time
  3. for i in range(10):
  4. print i
  5. try:
  6. time.sleep(1)
  7. except KeyboardInterrupt:
  8. break
处理方法二:
  1. #!/usr/bin/env python
  2. try:
  3. s = 100 / int(raw_input('enter a number: '))
  4. except (ValueError, ZeroDivisionError):
  5. print 'Invalid input'
  6. else:
  7. print s
处理方法三:
  1. #!/usr/bin/env python
  2. try:
  3. s = 100 / int(raw_input('enter a number: '))
  4. except ValueError:
  5. print 'Invalid input: Please input a number.'
  6. except ZeroDivisionError:
  7. print 'input a non-zero number.'
  8. else:
  9. print s
处理方法四:
  1. #!/usr/bin/env python
  2. try:
  3. s = 100 / int(raw_input('enter a number: '))
  4. except ValueError:
  5. print 'Invalid input: Please input a number.'
  6. except ZeroDivisionError, e:
  7. print 'Error: ', e
  8. else:
  9. print s
处理方法五;     不推荐这种方法
  1. #!/usr/bin/env python
  2. try:
  3. s = 100 / int(raw_input('enter a number: '))
  4. except:
  5. print 'Error'
处理方法六:
  1. #!/usr/bin/env python
  2. try:
  3. s = 100 / int(raw_input('enter a number: '))
  4. except (ValueError, ZeroDivisionError), e:
  5. print 'Error:', e
  6. else:
  7. print s
  8. finally:
  9. print 'Done.'
处理方法七:
  1. #!/usr/bin/env python
  2. i = 0
  3. while True:
  4. print i
  5. i += 1
  6. if i > 10:
  7. try:
  8. raise ValueError
  9. except ValueError:
  10. print 'Error'
  11. break
处理方法八:
  1. #!/usr/bin/env python
  2. i = 0
  3. while True:
  4. print i
  5. i += 1
  6. try:
  7. assert i < 5
  8. except AssertionError:
  9. break







posted @ 2016-12-19 14:25  Final233  阅读(166)  评论(0编辑  收藏  举报