美文网首页
笨办法学Python ex16

笨办法学Python ex16

作者: Joemini | 来源:发表于2016-12-11 17:27 被阅读0次

    读写文件


    应该记住的命令:

    • close -- 关闭文件。跟你编辑器的 文件->保存.. 一个意思。
    • read -- 读取文件内容。你可以把结果赋给一个变量。
    • readline -- 读取文本文件中的一行。
    • truncate -- 清空文件,请谨慎使用该命令。
    • write('stuff') -- 将 stuff 写入文件。

    <strong>要记住 write 需要接收一个字符串作为参数,从而将该字符串写入文件。

    • 输入:
    # -- coding: utf-8 --
    
    from sys import argv
    
    script, filename = argv
    
    print "We're going to erase %r." % filename
    print "If you don't want that, hit CTRL-C (^C)."
    print "If youdo want that, hit RETURN."
    
    raw_input("?")
    
    print "Opening the file..."
    target = open(filename, 'w') # 将文件对象赋值给 target
    
    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("\n") # 另起一行
    target.write(line2) # 写入命令
    target.write("\n") # 另起一行
    target.write(line3) # 输入需要写入的内容
    target.write("\n") # 另起一行
    
    print "And finally, we close it."
    target.close() # 保存文件内容,并关闭
    
    • 运行:


    附加题


    • 另外用argv和read写一个代码来读取刚刚写好的文件
    from sys import argv
    
    script, a = argv
    
    b = open(a) # 将文件对象赋值于b
    print b.read() # 读取文件命令
    
    • 只用一个target.write()将多行被赋值的变量写入文件

    目前水平不够,写不出来,以后再说。。。

    • 'w'参数是什么意思?

    它只是打开文件的一种模式。如果你用了这个参数,表示"以写(write)模式打开文件。同样有'r'表示只读模式,'a'表示追加模式,还有一些其他的修饰符。

    相关文章

      网友评论

          本文标题:笨办法学Python ex16

          本文链接:https://www.haomeiwen.com/subject/ihjpmttx.html