zoukankan      html  css  js  c++  java
  • 第一部分day5 文件操作

    #-----文件操作-----

    文件操作模式 1、"r" 读 2、"w" 清空写入 3、"a" 追加 4、"r+" 读写模式,可读可写 5、"w+" 写读模式,可写可读 6、"a+" 追加模式

    1 with open("小重山","r",encoding="utf-8") as f:
    2     data = f.read()
    3     print(data)
    4     f.close()
    readlines 方法
    1 with open("小重山","r",encoding="utf-8") as f:
    2     data = f.readlines()
    3     for i in data:
    4         print(i.strip())
    5 
    6 with open("小重山1","w",encoding="utf-8") as f:
    7     f.write("昨夜寒蛩不住鸣。惊回千里梦,已三更。起来独自绕阶行。")
    #在文件中第6行操作
     1 with open("小重山","r",encoding="utf-8") as f:
     2     # print(f.fileno()) #文件句柄 #3
     3     num1 = 0
     4     for i in f.readlines():
     5         num1 += 1
     6         if num1 == 6:
     7             i = ''.join([i.strip(),'ok'])
     8         print(i.strip())
     9 
    10 with open("小重山","r",encoding="utf-8") as f:
    11     num1 = 0
    12     for i in f:  #for循环内部将f 对象做成一个迭代器,用一行取一行
    13         num1 += 1
    14         if num1 == 4:
    15             i = "".join([i.strip(),"ok"])
    16         print(i.strip())
    #flush 方法(简单版进度条)
     1 import time,sys
     2 
     3 for i in range(30):
     4     sys.stdout.write("*")
     5     time.sleep(0.2)
     6     sys.stdout.flush()
     7 
     8 for i in range(30):
     9     print("*",end="",flush=True)
    10     time.sleep(0.2)
    #truncate 截断
    1 with open("小重山1","a",encoding="utf-8") as f:
    2     f.truncate(6) #昨夜
    #r+ 模式 光标以起始0开始
    1 with open("小重山1","a+",encoding="utf-8") as f:
    2     f.write("岳飞") #写入文件最后
    3     f.close()
    #w+ 模式
    1 with open("小重山1","w+",encoding="utf-8") as f:
    2     f.write("岳飞")
    3     print(f.tell()) #6
    4     f.seek(0)
    5     print(f.readline())
    #a+ 模式 光标以末尾开始
    1 with open("小重山1","a+",encoding="utf-8") as f:
    2     print(f.tell())
    3     f.write("岳飞")
    4     print(f.tell())
    5     print(f.readline())
    #文件修改
     1 # f_read = open("小重山1",'r',encoding="utf-8")
     2 # f_write = open("小重山2",'w',encoding="utf-8")
     3 #with 同时管理多个文件对象
     4 with open("小重山1",'r',encoding="utf-8") as f_read,open("小重山2",'w',encoding="utf-8") as f_write:
     5     num1 = 0
     6     for line in f_read:
     7         num1 += 1
     8         if num1 == 5:
     9             line = "".join([line.strip(),"dream
    "])
    10         f_write.write(line)
    11         print(line.strip())
    12     f_write.close()
    13     f_read.close()
  • 相关阅读:
    智力题:砝码称重问题
    Java:Comparator接口
    机器学习中比较重要的几个概念
    NLP:Gensim库之word2vec
    Java遍历Map对象的四种方式
    给数据库减负刻不容缓:多级缓存设计
    CentOS6.10安装redis5.0
    Linux下安装whl文件
    Linux下安装Gensim
    Linux下安装jieba
  • 原文地址:https://www.cnblogs.com/rise-home/p/11558095.html
Copyright © 2011-2022 走看看