习题16:读写文件

发布时间:2017-11-10 16:30:21编辑:Run阅读(3725)

    文件相关的命令(方法/函数),常用的命令如下

    close --- 关闭文件,跟你编辑器的 文件-->保存...一个意思

    read --- 读取文件内容,你可以把结果赋给一个变量

    readline --- 读取文本文件中的一行

    truncate --- 清空文件,请小心使用该命令

    write(stuff) --- 将stuff写入文件

    write需要接收一个字符串作为参数,从而将该字符串写入文件

    使用这些命令做一个简单的文本编辑器吧

    练习代码

    # coding: utf-8
    __author__ = 'www.py3study.com'
    from sys import argv
    script, filename = argv
    print("We're going to erase {}.".format(filename))
    print("If you don't want that,hit CTRL-C (^C)")
    print("If you do want that, hit RETURN.")
    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 = input("line 1:")
    line2 = input("line 2:")
    line3 = input("line 3:")
    print("I'm going to write there 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()

    小技巧就是可以让你的脚本一部分一部分地运行起来,也方便排查错误,以此类推,直到整个脚本运行起来为止

    跟上个练习一下,在当前目录创建一个test.txt文件

    运行命令

    python lianxi_16.py test.txt

    应该看到的结果

    E:\test>python lianxi_16.py test.txt
    We're going to erase test.txt.
    If you don't want that,hit CTRL-C (^C)
    If you do want that, hit RETURN.
    ?
    Opening the file...
    Truncating the file. GoodBye !
    Now I'm going to ask you for three lines.
    line 1:www.py3study.com
    line 2:py3study.com
    line 3:py3study
    I'm going to write there to the file.
    And finally, we close it.

    最后还可以验证一下,test.txt文件,看看里面是否有你写入的内容

    图片.png

    常见问题

    为什么'w'要放在括号中?

    w是指写入的意思,也就是write

    len()函数的功能是什么?

    它会以数字的形式返回你传递的字符串长度

    最后为什么要close?

    打开文件,对应的当然就需要保存文件,在java,C中如果不关闭文件,还会引起内存泄漏,总之一句话对文件操作完后,记得关闭文件


关键字