• python文件操作


    import os
    file=open('2.txt','r',encoding='utf-8')
    print(type(file))
    filecontent=file.read() #全读出来
    print(filecontent)
    file.close()

    print('*'*20)
    #按行读取
    fileline=open('2.txt','r',encoding='utf-8')
    linster=fileline.readline()
    while linster:
    print(linster,end='')
    linster=fileline.readline()
    fileline.close()

    print('')
    print('~'*20)
    #写入文本文件
    with open('1.txt','w',encoding='utf-8') as fp:
    fp.write('刘世奇is a 大傻逼')
    fp.flush()
    fp.close()


    #打开二进制文件
    with open(os.getcwd() +'/util/__pycache__/timeformatutil.cpython-36.pyc','rb') as fp:
    strb=fp.read()
    print(strb)
    fp.close()


    #向文件里追加内容a ab a=append
    file=open('3.txt','a',encoding='utf-8')
    file.write('hhhhhhhhhh 你大爷')
    file.close()


    import os
    import time

    def TimeStime(timestmp):
    timeStruct=time.localtime(timestmp)
    return time.strftime("%Y-%m-%d %H:%M:%S",timeStruct)

    #获取当前工作路径
    print(os.getcwd())
    #获取目录和文件名
    print(__file__)


    #获取文件的绝对路径,从根目录开始,不检查文件是否存在
    realpath=os.path.realpath('ajfagh.py')
    print(realpath)

    realdir=os.path.dirname(realpath)
    print(realdir)
    #获取路径下的文件名字
    print(os.path.basename(realpath))

    #获取文件的大小,时间,等属性
    #获取大小 单位字节
    size=os.path.getsize(__file__) #__file__意思为当前文件
    print(size)
    #返回的是时间戳格式。。。
    print(os.path.getctime(__file__))
    creattime=os.path.getctime(__file__)
    print('当前文件的创建时间:%s'%TimeStime(creattime))
    print(os.path.getatime(__file__))
    acesstime=os.path.getatime(__file__)
    print('当前文件的进入时间:%s'%TimeStime(acesstime))
    print(os.path.getmtime(__file__))
    modifytime=os.path.getmtime(__file__)
    print('当前文件的修改时间:%s'%TimeStime(modifytime))


    import os
    from week4_day01.util import timeformatutil
    #格式化时间的函数

    #work 读取路径下的全部文件,
    for root,dirs,files in os.walk('G:ceshi_music'):
    print('文件路径:%s'%root)
    print('路径下的文件夹:%s'%dirs)
    print('文件夹下的文件:%s' % files)
    if not os.path.exists('111.txt'):
    os.mkdir('111.txt')
    os.rmdir('111.txt')

    createtime=os.path.getctime(__file__)
    print('文件的创建时间为:%s'%timeformatutil.timestampformat(createtime))
  • 相关阅读:
    单元測试和白盒測试相关总结
    数据结构:图的实现--邻接矩阵
    Android提示版本号更新操作流程
    《集体智慧编程》代码勘误:第六章
    LINUX设备驱动程序笔记(三)字符设备驱动程序
    数学定理证明机械化的中国学派(II)
    《Java并发编程实战》第三章 对象的共享 读书笔记
    Linux系列-安装经常使用软件
    Kubuntu 初始配置
    虚拟互换(virtual swap)
  • 原文地址:https://www.cnblogs.com/yuxuanlian/p/9620424.html
Copyright © 2020-2023  润新知