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

2024-09-30 10:28:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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()语句,返回的文件路径始终是我的pycharm项目的脚本路径,也就是说"C:\Users\j2the\PycharmProjects\..."

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

注意:我的Pycharm配置不会有问题,因为我在空闲时运行了相同的代码,它仍然返回脚本路径

提前感谢您的帮助!:)


Tags: 文件函数代码路径src脚本文件夹for
1条回答
网友
1楼 · 发布于 2024-09-30 10:28:35

变量e只是文件名的字符串。它不包含任何关于它在哪里的信息。如果我们把它与the documentation of ^{}结合起来:

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.txt。而os.getcwd()是脚本运行的路径

看看the documentation for ^{},我们可以看到:

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)))

相关问题 更多 >

    热门问题