第15-17章文件读写,使用open,read,write,close函数,下面摘录原文的程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #! /usr/bin/env python #coding=utf-8 from sys import argvfrom os.path import existsscript, from_file, to_file = argv#argv类似c main(int arg,char× argv)命令行参数print "Copying from %s to %s" % (from_file, to_file)in_file = open(from_file)#打开文件indata = in_file.read()#读文件print "The input file is %d bytes long" % len(indata)#实际是string的长度print "Does the output file exist? %r" % exists(to_file)#判断路径存在性print "Ready, hit RETURN to continue, CTRL-C to abort."raw_input()out_file = open(to_file, 'w')out_file.write(indata)print "Alright, all done."out_file.close()in_file.close() |
第18-26变量,函数。之前都是调用库函数,现在学习自己写函数。函数以def 开始,形如下:
可见python的函数返回还是比c语言容易。
def print_one(arg1): #注意冒号换行后是四个空格,在专用的python里用tab键实际是自动替换了 print "arg1: %r" % arg1 #以下凡是以四个空格缩进的内容都是属于该函数 print "arg1: %r" % arg1print "hello" #新的开始def add(a, b):#带返回值的函数 print "ADDING %d + %d" % (a, b) return a + bdef mutireturn(a,b) return a,bdef multireturn(a,b):#python支持多返回值 return a,ba,b=multireturn(1,2)#注意返回值的数目和你接收的变量数目相等print "a=%r,b=%r" %(a,b)def multireturn2(a,b): return a,b,3a,b=multireturn2(1,2)#此处数目不等返回ValueError: too many values to unpackprint "a=%r,b=%r" %(a,b) |