为什么我的代码 return 脚本路径而不是绝对文件路径?

Why does my code return the scripth path instead of the absolute file path?

我在 Python 遇到了一个小问题,这让我抓狂。我的代码由一个非常简单的 os.walk() 函数组成,该函数应该在测试文件夹中找到所有文件及其路径(该测试文件夹由各种子文件夹组成)。

import os

src=r"C:\Users\j2the\Documents\Test3"

for dirpath,dirnames,filenames in os.walk(src):
    for e in filenames:
        print(e)
        print(os.path.abspath(e))

现在,当我 运行 代码时,它会打印出正确的文件名。但是,即使我使用了os.path.abspath() 语句,文件路径returned 始终是我的pycharm 项目的脚本路径,即"C:\Users\j2the\PycharmProjects\..."

那么为什么 Python return 脚本路径而不是文件的绝对路径,它应该类似于 "C:\Users\j2the\Documents\Test3\..."

注意:我的 Pycharm 配置不是问题,因为我 运行 在 IDLE 上使用了相同的代码并且它仍然 return 编辑了脚本路径

在此先感谢您的帮助! :)

变量e只是一串文件名。它不包含任何关于它在哪里的信息。如果我们将其与 the documentation of abspath:

Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).

因此 path 等于 e,这只是一个文件名,比如 my_file.txtos.getcwd() 是脚本 运行 来自的路径。

查看the documentation for os.walk,我们可以看到:

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

* 我的重点

现在我们可以将这两个知识结合起来产生这个:

import os

src=r"C:\Users\j2the\Documents\Test3"

for dirpath,dirnames,filenames in os.walk(src):
    for e in filenames:
        print(e)
        print(os.path.abspath(os.path.join(dirpath, e)))