python-06
#!/usr/bin/env python
#coding:utf8
import os
for tmpdir in ('/tmp', r'c:\temp'):
if os.path.isdir(tmpdir):
break
else:
print '没有这个目录'
tmpdir = ''
if tmpdir:
os.chdir(tmpdir)
cwd = os.getcwd()
print '当前临时目录'
print cwd
print '创建目录'
os.mkdir('example')
os.chdir('example')
cwd = os.getcwd()
print '新目录'
print cwd
print '列出目录'
print os.listdir(cwd)
fobj = open('test', 'w')
fobj.write('test1\n')
fobj.write('test2\n')
fobj.close()
print '更新目录列表'
print os.listdir(cwd)
print '重新改名'
os.rename('test', 'filetest.txt')
print '重新列出目录'
print os.listdir(cwd)
path = os.path.join(cwd, os.listdir(cwd)[0])
print '完整路径'
print path
print 'pathname, basename'
print os.path.split(path)
print '文件名, 扩展名'
os.path.splitext(os.path.basename(path))
print '显示文件内容'
fobj = open(path)
for eachline in fobj:
print eachline,
fobj.close()
print '删除test文件'
os.remove(path)
print '更新目录'
print os.listdir(cwd)
os.chdir(os.pardir)
print '删除test目录'
os.rmdir('example')
print 'END!'
异常
处理方法一:
#!/usr/bin/env python
import time
for i in range(10):
print i
try:
time.sleep(1)
except KeyboardInterrupt:
break
处理方法二:
#!/usr/bin/env python
try:
s = 100 / int(raw_input('enter a number: '))
except (ValueError, ZeroDivisionError):
print 'Invalid input'
else:
print s
处理方法三:
#!/usr/bin/env python
try:
s = 100 / int(raw_input('enter a number: '))
except ValueError:
print 'Invalid input: Please input a number.'
except ZeroDivisionError:
print 'input a non-zero number.'
else:
print s
处理方法四:
#!/usr/bin/env python
try:
s = 100 / int(raw_input('enter a number: '))
except ValueError:
print 'Invalid input: Please input a number.'
except ZeroDivisionError, e:
print 'Error: ', e
else:
print s
处理方法五; 不推荐这种方法
#!/usr/bin/env python
try:
s = 100 / int(raw_input('enter a number: '))
except:
print 'Error'
处理方法六:
#!/usr/bin/env python
try:
s = 100 / int(raw_input('enter a number: '))
except (ValueError, ZeroDivisionError), e:
print 'Error:', e
else:
print s
finally:
print 'Done.'
处理方法七:
#!/usr/bin/env python
i = 0
while True:
print i
i += 1
if i > 10:
try:
raise ValueError
except ValueError:
print 'Error'
break
处理方法八:
#!/usr/bin/env python
i = 0
while True:
print i
i += 1
try:
assert i < 5
except AssertionError:
break