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

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

    本节课在上一节的基础之上加入了对文件的写操作,代码较长,请注意不要有遗漏。

    原代码如下:

    from sys import argv
    
    script, filename = argv
    
    print "We are going to erase %r." % filename
    print "If you don't want to do that,hit CTRL-C (^C)."
    print "If you do want that, hit RETURN."
    
    raw_input("?")
    
    print "Opening the file..."
    target = open(filename, 'w')
    
    print "Truncating the file.Goodbye!"
    target.truncate()
    
    print "Now I'm going to ask you for three lines."
    
    line1 = raw_input("line 1:")
    line2 = raw_input("line 2:")
    line3 = raw_input("line 3:")
    
    print "I'm going to write these to the file."
    
    target.write(line1)
    target.write("
    ")
    target.write(line2)
    target.write("
    ")
    target.write(line3)
    target.write("
    ")
    
    print "And finally,we close it."
    target.close()

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

    请注意,我在出现前三行字符时,按的是回车键,按ctrl+c可以撤销操作。

    还是作者强调的,在打开一个文件,并进行完操作之后,记得关闭它们(“使用close()”)。

    至于target = open(filename, ‘w’)里面的w,我在上一节已经讲过了,不再赘述。

    本节课涉及的知识:

    变量名.函数,是使用函数对变量进行操作的方法,已经强调过,请牢记。

    至于write函数,括号里给出要写入的内容,字符串需要加“”,变量则不用,因此双引号的作用是将变量和字符串区分开来。

    请仔细阅读常见问题解答,并尝试记住他们。

  • 相关阅读:
    MYSQL 神奇的操作insert into test select * from test;
    mysql排序字段为空的排在最后面
    Redis有效时间设置及时间过期处理
    Dom4j 使用简介
    ASP.NET中使用多个runat=server form(转)
    谨以此文献给才毕业25年的朋友(转)
    门户网站
    庄思浩和BEA公司
    是什么限制了我们面向对象(的开发) (转)
    模态窗口和非模态窗口
  • 原文地址:https://www.cnblogs.com/wanghongze95/p/13842707.html
Copyright © 2011-2022 走看看