码迷,mamicode.com
首页 > 编程语言 > 详细

LPTHW 笨办法学python 20章

时间:2014-11-06 00:34:47      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   ar   for   sp   文件   div   on   

本章节讲述了,函数和文件的综合操作。

分别 执行了。1、读出文件所有内容,2、把文件重置至文件开头。3、打印一行。

 

我在本节作了一个小小的改良,设置了一个全局变量,记录当前应该输入哪一行,如果执行过一次,我就把这个行数加一。

 

代码部分如下:

 

#!/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):
    global line_no
    f.seek(0, 0)
    line_no = 1
def print_a_line(line_count,f):
    global line_no
    line_count = line_no
    print line_count,f.readline()
    line_no += 1

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:"
for i in xrange(3):
    print_a_line(line_no,current_file)

 

LPTHW 笨办法学python 20章

标签:style   blog   color   ar   for   sp   文件   div   on   

原文地址:http://www.cnblogs.com/sageskr/p/4077589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!