遍历文件夹中的所有文件并返回路径

-1 投票
1 回答
49 浏览
提问于 2025-04-14 17:21

基本上,我想要遍历文件夹里的所有文件,并返回它们的路径。这是我的文件夹结构,其中的 baby_names 文件夹包含我想要获取的信息。

FOLDER: (folder)
———main.py
———contents: (package)
——————babynames.py
——————baby_names: (folder)
—————————yob1880.txt
—————————yob1881.txt 
——————helper_functions: (package)
—————————hf.py

这是我的代码:

def retrieve_files(file_extension):
    """
    Go through folders in the Assignment 8, return a list
    containing the path and file name for every file with the specified extension.

    Args:
        file_extension (str)

    Returns:
        list: A list of file paths and names matching the specified extension.
    """
    file_paths = []
    for root, dirs, files in os.walk("Assignment8"):
        for file in files:
            if file.endswith(file_extension):
                file_paths.append(os.path.join(root, file))
    return file_paths

但是当我运行它的时候,它说没有找到任何文件。我也试着把文件路径调整为:Desktop/python 2/FOLDER,但还是不行。

1 个回答

0

编辑:

正如@s3dev提到的,我试了路径"N:/Code",结果成功了。所以我根据这个修改了我的回答。


确保你是在包含“Assignments”文件夹的目录下运行程序,而不是在其他地方。

我运行了你的代码,结果是可以的。问题可能出在你提供的路径或者你运行程序的地点。

下面是我运行的完整代码

import os


def retrieve_files(file_extension):
    """
    Go through folders in the Assignment 8, return a list
    containing the path and file name for every file with the specified extension.

    Args:
        file_extension (str)

    Returns:
        list: A list of file paths and names matching the specified extension.
    """
    file_paths = []
    for root, dirs, files in os.walk("N:\\Code"):
        for file in files:
            if file.endswith(file_extension):
                file_paths.append(os.path.join(root, file))
    return file_paths


jfiles = retrieve_files(".java")
for file in jfiles:
    print(file)

下面是我的PowerShell代码片段

PS N:\Code> python dfs.py
N:\Code\Java-Programs\hackerrank\minimum-swaps-2\Solution.java
N:\Code\Java-Programs\leetcode\contains-duplicate\Solution.java
N:\Code\Java-Programs\leetcode\decode-string\Solution.java

撰写回答