【问题标题】:Looping through Jupyter directory and adding file names to a list循环遍历 Jupyter 目录并将文件名添加到列表中
【发布时间】:2021-03-09 19:01:15
【问题描述】:

我有一个简单的文件设置(大约 15 个 .xlsx 文件在一个名为 FILE 的较大文件中,该文件位于 Jupyter 的主目录中)。我想遍历所有以特定字母组合开头的文件,然后将这些文件名添加到列表中。这是我到目前为止所拥有的。我想知道:1.正确的文件路径名是什么? 2. 如何返回想要的输出?

import os

directory = '???/'   <--- to find this enter pwd into cell

file_name_list = []

for filename in os.listdir(directory):
    if filename.startswith("SOME_LETTERS"):
        file_name_list.append(filename)
    else:
        continue

示例文件设置:

FILE --> 
SOME_LETTERS_1.xlsx 
DIFFERENT_LETTERS_1.xlsx
ONE_NUMBER. xlsx
SOME_LETTERS_2.xlsx
DIFFERENT_LETTERS_2.xlsx
SOME_LETTERS_3.xlsx
SOME_LETTERS_4.xlsx 

期望的输出:

[SOME_LETTERS_1, SOME_LETTERS_2, SOME_LETTERS_3, SOME_LETTERS_4] 

【问题讨论】:

    标签: python pandas for-loop directory jupyter


    【解决方案1】:

    使用 glob 模块https://docs.python.org/3/library/glob.html

    来自文档:

    glob 模块根据 Unix shell 使用的规则查找与指定模式匹配的所有路径名,尽管结果以任意顺序返回。不进行波浪号扩展,但 *、? 和用 [] 表示的字符范围将正确匹配。

    这是一个例子:

    from glob import glob
    
    for file in glob("path/to/some/folder/*.txt"):
        print(file)
    

    上面的代码将打印给定文件夹中所有 .txt 文件的名称。

    因此,在您的情况下,代码将类似于:

    """
    Folder structure:
    ├── samples
    │   ├── Asample2.txt
    │   ├── Bsample4.txt
    │   ├── sample3.txt
    │   ├── sample5.txt
    │   └── sample.txt
    └── stack.py
    """
    
    from glob import glob
    import os
    
    # Using os.path.join so it works on multiple platforms
    dir = os.path.join("samples", "*.txt")
    
    
     # os.path.basename extracts the file name from the fullpath
    file_name_list = [file for file in glob(dir) if os.path.basename(file).startswith("s")]
    print(file_name_list)
    >>>['samples/sample5.txt', 'samples/sample.txt', 'samples/sample3.txt']
    

    另一种方法可以通过使用 Unix 扩展来实现:

    from glob import glob
    import os
    
    # Some letter here: ---------
    #                             \
    #                              v
    dir = os.path.join("samples", "s*.txt")
    
    file_name_list = [file for file in glob(dir)]
    print(file_name_list)
    

    【讨论】:

    • 是的,但我不想要所有文件 - 我只想要以字母组合开头的文件,我想将它们添加到列表中。
    • 需要定义目录吗?我得到一个空列表
    • 是的,您确实需要一个目录。不带过滤器试试,看看结果,问题可能是路径错误或过滤器错误;
    • 感谢您的解释!它奏效了,我在这个过程中学到了一两件事:)
    猜你喜欢
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多