zoukankan      html  css  js  c++  java
  • 《笨办法学Python》 第20课手记

    《笨办法学Python》 第20课手记

    本节课讲函数与文件,内容比较简单,但请注意常见问题解答,你应该记住那些内容。

    指针表示存储地址。

    原代码如下:

    from sys import argv #从sys模组中引入argv
    
    script, input_file = argv #将argv的列表变量赋值给script和input_file
    
    def print_all(f): #定义一个打印文件的函数
      print f.read() #函数主体,打印从f变量中读取的内容
    
    def rewind(f): #定义一个复读函数
      f.seek(0) #函数主体使用seek设置文件(指针)的偏移。这里,作者想要你知道它的存在,看不懂先记住就好
    
    def print_a_line(line_count, f): #定义一个只打印一行的函数,并将文件内部指针移向下一行
      print line_count, f.readline()
    
    current_file = open(input_file) #使用open函数打开文件,并赋值给curren_file(文件变量)
    
    print "Now let's print the whole file:
    "
    
    print_all(current_file) #调用函数print_all
    
    print "Let's rewind, kind of like a tape."
    
    rewind(current_file) #调用函数rewind,rewin读取的是文件内部的指针,而不是文件的指针
    
    print "Let's print three lines:"
    
    current_line = 1 #current_line表示行号的变量,首先置1
    print_a_line(current_line, current_file)  #调用print_a_line函数,下同
    
    current_line = current_line + 1 #行号加1
    print_a_line(current_line, current_file)
    
    current_line = current_line + 1 #行号加1
    print_a_line(current_line, current_file)

    结果如下:
    这里写图片描述

    本节课涉及的内容

    Python中对于本节课涉及到的部分函数的解释:

    使用 python -m podoc file 可查看,你需要按下回车以显示更多内容才能看到这里

    这里写图片描述

    seek函数:
    file.seek(offset[, whence])

    offset: 文件的读/写指针位置。
    whence: 这是可选的,默认为0,这意味着绝对的文件定位,其他值是1,这意味着当前的位置和2手段寻求相对寻求相对文件的结束。

    f.seek(0)表示将指针转移到文件的0byte位置,即开始位置。

    readline读取一行之后会将文件内部的指针移向下一行,下次调用readline则会读取下一行位置。

  • 相关阅读:
    【协议分析】Wireshark 过滤表达式实例
    学习Javascript闭包(Closure)
    如何解决 touchstart 事件与 click 事件的冲突
    JS实现控制HTML5背景音乐播放暂停
    $.ajax()方法详解
    js将汉字转为相应的拼音
    js 滚动到一定位置导航定位在页面最顶部
    javascript获取网页地址栏的id
    jquery 上传图片转为base64,ajax提交到后台
    jquery 图片转为base64
  • 原文地址:https://www.cnblogs.com/wanghongze95/p/13842703.html
Copyright © 2011-2022 走看看