zoukankan      html  css  js  c++  java
  • day08文件的操作(0221)

    #1、文件操作之追加数据01:
    f = open("yesterday01",'a+U',encoding="utf-8")
    #a= append,追加之意,w则为写入并覆盖,r为只读,+表示可同时读写,
    # U表示在读取时,可以将 自动转换为 ,如 r+U,b表示处理的是二进制文件(如ftp需用rb,wb)

    f.write(" when i was young I like to listen to the radio ")
    data = f.read()
    print(data)
    f.close()

    #2、文件操作之读前3行的数据:
    f = open("yesterday01","r",encoding="utf-8")
    for i in range(3):
    print(f.readline())

    #3、打印所有的行:
    f = open("yesterday01","r",encoding="utf-8")
    for line in f.readlines():
    print(line)

    #4、以下的作用待查:
    f = open("yesterday01","r",encoding="utf-8")
    for line in f.readlines():
    #print(f.readline())
    print(f.tell())
    f.seek(2)
    print(f.readline())

    #5、打印出修改的内容并写入备份的文档中:
    f = open("yesterday01","r+",encoding="utf-8")
    f_bak = open("yesterday01bak","a+",encoding="utf-8")

    for line in f.readlines(): #注意是带s的,()表示所有
    if "raddio" in line:
    line = line.replace("raddio","MP3")
    f_bak.write(line)
    print (line)
    f.close()
    f_bak.close()

    #6、回车键:
    f = open("yesterday01","a+",encoding="utf-8")
    f.write("---hello------ ")
    f.write("---hello------ ")
    f.write("---hello------ ")

    #7、??:
    import sys
    f = open("yesterday01","r+",encoding="utf-8")
    f_bak = open("yesterday01bak","a+",encoding="utf-8")
    find_str = sys.argv[1]
    replace_str = sys.argv[2]
    for line in f.readlines():
    if find_str in line:
    line = line.replace(find_str,replace_str)
    f_bak.write(line)
    print (line)
    f.close()
    f_bak.close()

    #8、不需要用close关闭文件的方法(读最前面的42个字符,不足一行则显示一行的内容):
    with open("yesterday01","r+",encoding="utf-8") as f:
    for line in f.readlines(42):
    print (line)
  • 相关阅读:
    MySQL数据库基本操作(二)
    MySQL数据库基本操作(一)
    13.常见模块re-正则模块
    12.常见模块time、json模块
    11.迭代器与生成器、模块与包
    10.文件的输入输出、异常
    9.多继承、类的特殊方法、装饰器
    8.类的概念、定义、属性、继承
    7.内置函数、作用域、闭包、递归
    6.函数基础
  • 原文地址:https://www.cnblogs.com/liulvzhong/p/6425388.html
Copyright © 2011-2022 走看看