Hetian lab day 5 Python 编程进阶(上)

22 篇文章 0 订阅
13 篇文章 0 订阅

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

模块处理

support.py

def printme(param):# this is a module
    print "hello :",param
    return
def calculate(a , b):
    return a**b
 </code>

support1.py

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')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值