文章目录
Part 1 Python 编程进阶(上) 课后题
【解析】
【解析】
Part 2 实验操作
文件IO
content
raw_input(“input string:”)
input(“input expression:”)
file
open()
fp=open(filename,[access_mode])
fp.closed,return True or False
fp.mode,return access mode
fp.name,return file name
fp.softspace,return whether there is a space,true or false
close()
fp.close()
write()
fp.write(“contents \n”)
read()
fp.read(length)
path
fp.tell(),current file position
rename()
import os
os.rename(a.format,aNew.format)
remove()
import os
os.remove(“name.format”)
directory
mkdir
create a new folder
rmdir
delete a folder
chdir
change the current directory
getcwd()
show the current work directory
模块处理
def printme(param):# this is a module
print "hello :",param
return
def calculate(a , b):
return a**b
</code>
def add(pa1,pa2):
return pa1+pa2
def sub(pa1,pa2):
if pa1<pa2:
t=pa1
pa1=pa2
pa2=pa1
return pa1-pa2
def mul(pa1,pa2):
return pa1*pa2
hello.py
#!/usr/bin/env python
# coding=utf-8
import support as sp# import the module you write
import support1
sp.printme("zl~")
a=input("a=")
b=input("b=")
print sp.calculate(a,b)
print support1.add(a,b)
# dir()函数一个排好序的字符串列表,内容是一个模块里定义过的名字。返回的列表容纳了在一个模块里定义的所有模块,变量和函数。
print dir(support1)# print all the module\variable\function
异常处理
#!/usr/bin/env python
#coding=utf-8
import time
try:# 先执行try后语句,异常则到except,成功则到else
fp=open("LICENSE","r")
except IOError:
print "Error: can't find file or read data"
else:
print "written content in the file succesfully"
fp.close()
try:# try...finally:no matter whether there is except, the last lin of code will be execute.
fp=file('poem.txt')
while True:
line=fp.readline()
if len(line)==0:
break
time.sleep(2)
print line
finally:
fp.close()
print 'Cleaning up...closed the file'
filename=raw_input('please input file name:')
if filename=='hello':# trick the except manually
raise NameError('input file name error')