我在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配置不会有问题,因为我在空闲时运行了相同的代码,它仍然返回脚本路径
提前感谢您的帮助!:)
变量} 结合起来:
e
只是文件名的字符串。它不包含任何关于它在哪里的信息。如果我们把它与the documentation of ^{因此
path
等于e
,这只是一个文件名,比如说my_file.txt
。而os.getcwd()
是脚本运行的路径看看the documentation for ^{} ,我们可以看到:
*我的重点
现在,我们可以将这两项知识结合起来,得出以下结论:
相关问题 更多 >
编程相关推荐