《笨方法学习python3》练习16: Reading and Writing Files: write, seek, readline, truncate, open

EX16: Reading and Writing Files

  • 例子:

    from sys import argv
    
    script, filename = argv
    
    print(f"We're going to erase {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...")
    # w 新建只写,w+ 新建读写,二者都会将文件内容清零(以 w 方式打开,不能读出。w+ 可读写)
    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 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()
    

    没有target.close(),文件内容也会保存。但是这个命令非常有必要,特别是用.write()做循环时。当程序越来越复杂时,如果没有close()命令,会导致文件一直运作,直到电脑崩溃。

  • 学习内容:readline()write()seek()truncate()open()中的wwbw+rrbr+aa+

    • readline()
      • readline()方法每次读取一行;返回的是一个字符串对象,保持当前行的内存

      • readline() 读取整行,包括行结束符,并作为字符串返回

      • read()readline()readlines()的区别

        read():读取整个文档,直接读取字节到字符串中,包括了换行符

        readline():每次只读取一行,读取后再次执行该命令,会读取下一行

        readlines():一次性读取整个文件;自动将文件内容分析成一个行的列表

        输入:

        from sys import argv
        script, filename = argv
        
        txt = open(filename, 'r')
        a = txt.read()
        txt.seek(0)
        b = txt.readline()
        txt.seek(0)
        c = txt.readlines()
        
        print("用read()读取文档: " , a)
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值