• python之文件读取


    python提供三种扫描当前路径的方法:os.listdir, os.scandir和pathlib

    FunctionDescription
    os.listdir() Returns a list of all files and folders in a directory
    os.scandir() Returns an iterator of all the objects in a directory including file attribute information
    pathlib.Path.iterdir() Returns an iterator of all the objects in a directory including file attribute information

    以上三种方法都可以列出当前目录中的所有文件和子路径,但如果当我们需要个性化过滤的时候,就需要到以下操作:

    1)仅列出所有文件:

    import os
    
    # List all files in a directory using os.listdir
    basepath = 'my_directory/'
    for entry in os.listdir(basepath):
        if os.path.isfile(os.path.join(basepath, entry)):
            print(entry)
    
    import os
    
    # List all files in a directory using scandir()
    basepath = 'my_directory/'
    with os.scandir(basepath) as entries:
        for entry in entries:
            if entry.is_file():
                print(entry.name)
    
    from pathlib import Path
    
    basepath = Path('my_directory/')
    files_in_basepath = basepath.iterdir()
    for item in files_in_basepath:
        if item.is_file():
            print(item.name)

    2)仅列出所有子路径

    import os
    
    # List all subdirectories using os.listdir
    basepath = 'my_directory/'
    for entry in os.listdir(basepath):
        if os.path.isdir(os.path.join(basepath, entry)):
            print(entry)
    
    
    # List all subdirectories using scandir()
    basepath = 'my_directory/'
    with os.scandir(basepath) as entries:
        for entry in entries:
            if entry.is_dir():
                print(entry.name)
    
    
    # List all subdirectory using pathlib
    basepath = Path('my_directory/')
    for entry in basepath.iterdir():
        if entry.is_dir():
            print(entry.name)

    3)匹配特定类型文件,如txt

    >>> for filename in os.listdir('.'):
    ...     if fnmatch.fnmatch(filename, 'data_*_backup.txt'):
    ...         print(filename)

    python还提供了从linux到windows的兼容路径查找工具glob,利用glob和Unix系统中“*”,“?"的特殊语法,可以做到递归查找特定类型文件

    >>> import glob
    >>> for file in glob.iglob('**/*.py', recursive=True):
    ...     print(file)

    pathlib也有类似Unix的操作

    >>> from pathlib import Path
    >>> p = Path('.')
    >>> for name in p.glob('*.p*'):
    ...     print(name)

    其他更多高级操作见参考资料[1]

    参考资料:

    [1]Working With Files in Python

    https://realpython.com/working-with-files-in-python/

  • 相关阅读:
    直播实录: 零售金融线上风控的规划与实践
    暖春行动护航"多投票平台”,助力数字经济发展
    顶象助力伍拾度,打造公正公平投票平台
    “2019人工智能案例TOP100”榜发布,顶象与众邦银行均入选
    风控四件套全年免费活动发布一周后,7个与你相关的问题
    WPF自学入门(八)WPF窗体之间的交互
    WPF自学入门(七)WPF 初识Binding
    WPF自学入门(六)WPF带标题的内容控件简单介绍
    WPF自学入门(五)WPF依赖属性
    WPF自学入门(四)WPF路由事件之自定义路由事件
  • 原文地址:https://www.cnblogs.com/J14nWe1/p/14661557.html
Copyright © 2020-2023  润新知