• 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)
  • 相关阅读:
    POJ3613 Cow Relays [矩阵乘法 floyd类似]
    BZOJ 2302: [HAOI2011]Problem c [DP 组合计数]
    BZOJ 1037: [ZJOI2008]生日聚会Party [序列DP]
    BZOJ 1898: [Zjoi2005]Swamp 沼泽鳄鱼 [矩阵乘法]
    Codeforces Round #390 (Div. 2)
    BZOJ 1096: [ZJOI2007]仓库建设 [斜率优化DP]
    BZOJ 1911: [Apio2010]特别行动队 [斜率优化DP]
    BZOJ 1597: [Usaco2008 Mar]土地购买 [斜率优化DP]
    [斜率优化DP]【学习笔记】【更新中】
    BZOJ 2127: happiness [最小割]
  • 原文地址:https://www.cnblogs.com/liulvzhong/p/6425388.html
Copyright © 2020-2023  润新知