笨办法学Python——学习笔记2

    第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  argv
from  os.path  import  exists
script, 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()
可见文件读写和c语言类似,查看api手册即可。
    第18-26变量,函数。之前都是调用库函数,现在学习自己写函数。函数以def 开始,形如下:
?
def  print_one(arg1):  #注意冒号换行后是四个空格,在专用的python里用tab键实际是自动替换了
     print  "arg1: %r"  %  arg1  #以下凡是以四个空格缩进的内容都是属于该函数
     print  "arg1: %r"  %  arg1
print  "hello"  #新的开始
def  add(a, b): #带返回值的函数
     print  "ADDING %d + %d"  %  (a, b)
     return  +  b
def  mutireturn(a,b)
     return  a,b
def  multireturn(a,b): #python支持多返回值
     return  a,b
a,b = multireturn( 1 , 2 ) #注意返回值的数目和你接收的变量数目相等
print  "a=%r,b=%r"  % (a,b)
def  multireturn2(a,b):
     return  a,b, 3
a,b = multireturn2( 1 , 2 ) #此处数目不等返回ValueError: too many values to unpack
print  "a=%r,b=%r"  % (a,b)
可见python的函数返回还是比c语言容易。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值