• python基础--文件操作


    1)目录

    手动挡open+close:
    open
    close
    自动挡with,自动关闭
    
    #1常见操作:
    w,r,a, b
    write
    readline
    readlines
    seek  #设置从那个位置读取
    tell  #获取文件现在读取位置
    read
    
    #相关模块
    fnmatch
    glob
    pickle
    StringIO
    shelve
    

    2)文件操作

    f = open('文件名或类似文件的东西', ’文件打开模式')
    # f是文件对象或指针,用来进行读写操作
    f.close
    
    # 三种模式
    w, write, 写
    r,read,读
    a, append,追加内容
    
    
    #示例1:写文件,用w方式打开文件,不存在则创建
    f = open('111.txt', 'w') # 用w方式打开文件,不存在则创建
    f.write('111' * 8) # 写入字符串
    f.close()
    
    #示例2:with方式打开,文件会自动关闭
    with open('111-1.txt', 'w') as f:#文件会自动关闭
        f.write('111')
    
    #示例3:文件名后面的r模式默认
    with open('111.txt') as f: # 文件名后面的r模式默认
        data = f.read() # 读出所有内容, 保存到一个变量,文件不存在读会报错
        print(data)
    
    #示例4:读取一行
    with open('111.txt') as f:
        print(f.readline()) #读取一行
    
    #示例5:'a' 多几行,追加到源文件
    with open('111.txt', 'a') as f: # 'a' 多几行,追加到源文件
        f.write('111111
    ')
        f.write('111111
    ')
    
    #示例6:readlines读成列表
    with open('111.txt') as f:
        print(f.readlines())
        #['11111
    ', '111111
    ', '
    ', '111111
    ', '111111']
    
    #示例7:tell seek
    f = open('de8ug.txt')
    print(f.tell())
    print(f.readline())
    print(f.tell())
    print(f.readline())
    print(f.tell())
    f.seek(0)
    print(f.tell())
    print(f.readline())
    f.seek(0)
    print(f.readline())
    
    #------------------------------
    0
    11111111111
    10
    111111
    22222222222
    20 
    0
    11111111111
    0
    11111111111
    

    3)相关模块

    1)fnmatch
    
    # fnmatch匹配相应后缀名的文件
    import fnmatch
    for f in os.listdir('test'):
        if fnmatch.fnmatch(f, '*.txt'): #支持正则表达式
            print(f)
        elif fnmatch.fnmatch(f, '*.pdf'):
            print('find pdf', f)
    
    # fnmatch 匹配相应后缀名的文件
    import fnmatch
    for f in os.listdir('test'):
        if fnmatch.fnmatch(f, '?.txt'): # 正则,?匹配一个字符
            print(f)
        elif fnmatch.fnmatch(f, '?.pdf'): # 正则,?匹配一个字符
            print('find pdf', f)
    
    2)glob
    #单纯匹配某种命名规则文件
    import glob
    for f in glob.glob('test/[0-9].doc'):
        print(f)
    
    3)StringIO
    # 虚拟文件,临时文件,不需要真的保存文件到磁盘
    import io
    output = io.StringIO()
    output.write('第2行代码
    ')
    print('试一下print到文件:', file=output)
    # 取出内容
    contents = output.getvalue()
    print(contents)
    # 关闭文件,清理缓存
    output.close()
  • 相关阅读:
    usaco 1.11
    当数组时全局变量时。。。怎样进行循环初始化
    hdu 1097 用到了位的移动
    hdu 1006
    HNOI2008]神奇的国度
    App测试基本流程详解(汇总整理)
    IOS测试Fastmonkey
    pytest+allure2+jenkins环境部署
    如何在cmd查看文件内容的md5值
    软件测试学习linux基础
  • 原文地址:https://www.cnblogs.com/lixiang1013/p/9216294.html
Copyright © 2020-2023  润新知