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

      

      

    草都可以从石头缝隙中长出来更可况你呢
  • 相关阅读:
    Two Sum
    Binary Tree Preorder Traversal *
    Rotate Array
    Repeated DNA Sequences
    Symmetric Tree
    Path Sum
    Python初学——多线程Threading
    Python初学——窗口视窗Tkinter
    pyinstaller打包多个py文件和去除cmd黑框
    python获取当前路径
  • 原文地址:https://www.cnblogs.com/rdchenxi/p/11122738.html
Copyright © 2020-2023  润新知