练习17
# --coding:utf-8--
from sys import argv
from os.path import exists
script,from_file,to_file = argv #分别代表脚本名称,源文件名,目标文件名
print "Copying from %s to %s" %(from_file,to_file)
# we could do these two on one line too,how?
input = open(from_file) #将用户输入的文件赋给input变量
indata = input.read() #读取文件内容
print "The input file is %d bytes long" %len(indata) #len()函数可以返回字符串的字节数
print "Does the output file exist?%r" %exists(to_file) #exists()函数可以判断该文件是否存在
print "Ready,hiit RETUTN to continue,CTRL-C to abort."
raw_input()
output = open(to_file,'w') #以写模式打开目标文件,赋给output变量
output.write(indata) #将数据写入目标文件
print "Alright,all done."
output.close() #保存文件
input.close() #保存文件
练习18
# --coding:utf-8--
# this one is like your sripts with argv
def print_two(*args): #定义了一个函数,可以打印两个参数
arg1,arg2 = args
print "arg1:%r,arg2:%r" %(arg1,arg2)
# ok,that *args is actually pointless,we can just do this
def print_two_again(arg1,arg2):
print "arg1: %r,arg2:%r" %(arg1,arg2)
# this just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1
#this one takes no arguments
def print_none():
print "I got nothing."
print_two("li","jia") #调用函数
print_two_again("wei","learn")
print_one("python")
print_none()
1.创建一个函数,首先使用def命令,也就是定义的意思
2.紧接着def后面的是函数的名称
3.接下来是参数列表,然后使用冒号结束本行,下一行开始需要使用缩进。
练习19
# --coding:utf-8--
# 在函数的参数列表里使用变量
def cheese_and_crackers(cheese_count,boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxed of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbers directly:"
cheese_and_crackers(20,30)
print "OR,we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese,amount_of_crackers)
print "We can even do math inside too:"
cheese_and_crackers(10+20,5+6)
print "And we can combine the two,variables and math:"
cheese_and_crackers(amount_of_cheese+100,amount_of_crackers+1000)
练习20
# --coding:utf-8--
from sys import argv
script,input_file = argv
def print_all(f): #打印文件内容,f是文件
print f.read()
def rewind(f): #seek函数暂时还没搞懂
f.seek(0)
def print_a_line(line_count,f): #打印一行
print line_count,f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind,kind of like a tape."
rewind(current_file) #这句如果注释掉,后面就无法打印出每一句的内容
print "Let's print three lines:"
current_line = 1
print_a_line(current_line,current_file)
current_line = current_line + 1
print_a_line(current_line,current_file)