zoukankan      html  css  js  c++  java
  • 笨办法16读写文件

    代码如下:

     1 #coding:utf-8
     2 from sys import argv
     3 
     4 script, filename = argv
     5 
     6 print "We're going to erase %r." %filename #提示语句,告知用户将抹掉文件
     7 print "If you don't want that, hit CTRL-C (^C)." #提示语句,停止操作的按键
     8 print "If you do want that, hit RETURN." #提示语句,继续操作的按键
     9 
    10 raw_input("?") #让用户输入是否要继续操作
    11 
    12 print "Opening the file..." #提示语句,正在打开文件
    13 target = open(filename, 'w') #将打开的文件清空并赋值给target,w不能大写
    14 
    15 print "Truncating the file. Goodbye!" #提示语句,正在清空文件
    16 target.truncate() #执行清空文件操作#truncate()其实是不需要的,因为open的参数是w
    17 
    18 print "Now I'm going to ask you for three lines." #提示语句
    19 
    20 line1 = raw_input("line 1:") #输入第一行的内容
    21 line2 = raw_input("line 2:") #输入第二行的内容
    22 line3 = raw_input("line 3:") #输入第三行的内容
    23 
    24 print "I'm going to write these to the file." #提示语句
    25 
    26 target.write(line1) #写入第一行的内容
    27 target.write("
    ") #写入换行符
    28 target.write(line2)
    29 target.write("
    ")
    30 target.write(line3)
    31 target.write("
    ")
    32 
    33 print "And finally, we close it." #提示关闭文件
    34 target.close() #关闭(保存)文件

    运行结果: 
    这里写图片描述

    新增的文件内容: 
    这里写图片描述

    注: 
    ‘w’:以只写模式打开。若文件存在,则会自动清空文件,然后重新创建;若文件不存在,则新建文件。使用这个模式必须要保证文件所在目录存在,文件可以不存在。该模式下不能使用read*()方法


    加分练习2:代码如下

    1 print "Please enter your filename, and I'll read it."
    2 
    3 filename = raw_input(">")
    4 txt = open(filename)
    5 print txt.read()

    运行结果: 
    这里写图片描述


    加分练习3:写了两种方法

    1 #target.write(line1+"
    "+line2+"
    "+line3) #变量不需加引号,字符串需要加双引号#a+b参考第6课
    2 target.write("%s
    %s
    %s" % (line1, line2, line3)) #这里如果用%r,文件的每行字符会有引号

    加分练习4:找出为什么我们需要给 open 多赋予一个 ‘w’ 参数。提示: open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作。 
    因为默认open只能读取不能写入,所以要写入内容就必须加入’w’参数。 
    truncate()其实是不需要的,因为open的参数是w

  • 相关阅读:
    BZOJ 1726: [Usaco2006 Nov]Roadblocks第二短路
    BZOJ 1708: [Usaco2007 Oct]Money奶牛的硬币
    BZOJ 1642: [Usaco2007 Nov]Milking Time 挤奶时间
    BZOJ 1611: [Usaco2008 Feb]Meteor Shower流星雨
    BZOJ 1610: [Usaco2008 Feb]Line连线游戏
    BZOJ 1609: [Usaco2008 Feb]Eating Together麻烦的聚餐
    BZOJ 1607: [Usaco2008 Dec]Patting Heads 轻拍牛头
    BZOJ 1606: [Usaco2008 Dec]Hay For Sale 购买干草
    BZOJ 1083: [SCOI2005]繁忙的都市
    STL set的用法
  • 原文地址:https://www.cnblogs.com/p36606jp/p/7648183.html
Copyright © 2011-2022 走看看