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
    漫作年时别泪看。西窗蜡炬尚澜。不堪重梦十年间。
    斗柄又垂天直北,客愁坐逼岁将阑。更无人解忆长安。
    

      

      

    草都可以从石头缝隙中长出来更可况你呢
  • 相关阅读:
    SqlServer事务语法及使用方法
    mysql解决自动断开8小时未曾用过的链接
    JIRA license申请和语言包下载
    String literal is not properly closed by
    android开发 NDK 动态链接多个第三方库(so)
    vim字符串替换
    VMware tools的用途及安装[跨系统文件拖拽]
    十大高明的Google搜索技巧
    安装ADT-20.0.3的时候产生org.eclipse.cdt.feature.group 0.0.0' but it could not be ..
    [Android NDK]修复/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory 问题
  • 原文地址:https://www.cnblogs.com/rdchenxi/p/11122738.html
Copyright © 2011-2022 走看看