zoukankan      html  css  js  c++  java
  • python 基础文件操作

    实时刷新到硬盘里

    f= open('hh','w',encoding='utf8')
    f.write('gyftyftft')
    f.write('hghgh
    jkkjk')
    f.flush()#实时写到硬盘
    

     打印下载条目

    import sys,time #加载模块
    for i in range(30):
        sys.stdout.write('*')#打印*
        sys.stdout.flush()  #实时刷到磁盘
        time.sleep(0.2)#延迟0.2秒
    

      测试

    D:pythonpython.exe D:/untitled/dir/for.py
    ******************************
    Process finished with exit code 0
    

      原文

    nihao chenxi haha woai ni
    漫作年时别泪看。西窗蜡炬尚澜。不堪重梦十年间。
    斗柄又垂天直北,客愁坐逼岁将阑。更无人解忆长安。
    

      只留文件前五个字符

    o = open('尘曦','a',encoding='utf8')
    
    o.truncate(5)
    o.close()
    

      运行代码后查看

    nihao
    

      文件操作模式之r+模式

    o = open('尘曦','r+',encoding='utf8')
    print(o.read())
    o.close()
    o.write('岳飞')# 注意加到最后
    print(o.read())
    o.close()
    

      测试

    D:pythonpython.exe D:/untitled/dir/for.py
    nihao chenxi haha woai ni
    
    漫作年时别泪看。西窗蜡炬尚澜。不堪重梦十年间。
    斗柄又垂天直北,客愁坐逼岁将阑。更无人解忆长安。岳飞
    
    Process finished with exit code 0
    

      文件操作之w+

    o = open('尘曦','w+',encoding='utf8')
    print(o.readline())
    o.write('岳飞')
    #print(o.tell())
    o.seek(0)
    print(o.read())
    o.close()
    

      测试 

    D:pythonpython.exe D:/untitled/dir/for.py
    
    岳飞
    
    Process finished with exit code 0
    

         原文

    nihao chenxi haha woai ni
    
    漫作年时别泪看。西窗蜡炬尚澜。不堪重梦十年间。
    斗柄又垂天直北,客愁坐逼岁将阑。更无人解忆长安。  

    文件操作之a+

    o = open('尘曦','a+',encoding='utf8')
    print(o.readline())
    o.write('岳飞')
    o.seek(0)
    print(o.read())
    o.close()
    

      测试

    nihao chenxi haha woai ni
    
    漫作年时别泪看。西窗蜡炬尚澜。不堪重梦十年间。
    斗柄又垂天直北,客愁坐逼岁将阑。更无人解忆长安。岳飞
    

         原文

    生当作人杰,死亦为鬼雄。
    至今思项羽,不肯过江东。
    漫作年时别泪看。西窗蜡炬尚澜。不堪重梦十年间。
    斗柄又垂天直北,客愁坐逼岁将阑。更无人解忆长安。

     文件修改操作

    f_red = open('尘曦','r',encoding='utf8')
    f_write = open('尘曦-3','w',encoding='utf8')
    number = 0
    for line in f_red:
        number+=1
        if number==2:
            #line=''.join([line.strip(),'chenxi'])
            line='hello chenxi
    '
        f_write.write(line)
    
    f_red.close()
    f_write.close()
    

      测试

    生当作人杰,死亦为鬼雄。
    hello chenxi
    漫作年时别泪看。西窗蜡炬尚澜。不堪重梦十年间。
    斗柄又垂天直北,客愁坐逼岁将阑。更无人解忆长安。
    

      

      

    草都可以从石头缝隙中长出来更可况你呢
  • 相关阅读:
    RecyclerView 数据刷新的几种方式 局部刷新 notify MD
    【图片】批量获取几万张图片
    RV BaseRecyclerViewAdapterHelper 总结 MD
    RecyclerView.ItemDecoration 间隔线
    Kotlin【简介】Android开发 配置 扩展
    Kotlin 特性 语法糖 优势 扩展 高阶 MD
    一个十分简洁实用的MD风格的UI主框架
    折叠伸缩工具栏 CollapsingToolbarLayout
    FloatingActionButton FAB 悬浮按钮
    Glide Picasso Fresco UIL 图片框架 缓存 MD
  • 原文地址:https://www.cnblogs.com/rdchenxi/p/11122738.html
Copyright © 2011-2022 走看看