第20个python程序:函数和文件

来源:互联网 发布:淘宝打印电子面单 编辑:程序博客网 时间:2024/05/29 08:25
[root@mysql1 pshell]# cat ex20.py 
#!/usr/bin/env Python
#-*-coding:utf-8-*-


from sys import argv


script,input_file=argv


def print_all(f):
  print f.read()


def rewind(f):
  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)
current_line=current_line+1
print_a_line(current_line,current_file)
[root@mysql1 pshell]# 
[root@mysql1 pshell]# 
[root@mysql1 pshell]# 
[root@mysql1 pshell]# python ex20.py test.txt
first let's print the whole file:


111111
22222222
3333333333
aaaaaa
bbbbbbbb
ccccccccccc


now let's rewind,kind of like a tape.
let's print three lines:
1 111111


2 22222222


3 3333333333
0 0