我在网站上阅读了很多链接说要使用“os.path.abspath(#filename)”。这种方法并不完全适合我。我正在编写一个程序,该程序将能够在给定目录中搜索具有某些扩展名的文件,将名称和绝对路径作为键和值(分别)保存到字典中,然后使用绝对路径打开文件并制作所需的编辑。我遇到的问题是,当我使用 os.path.abspath() 时,它没有返回完整路径。
假设我的程序在桌面上。我有一个文件存储在“C:\Users\Travis\Desktop\Test1\Test1A\test.c”。我的程序可以轻松找到此文件,但是当我使用 os.path.abspath() 时,它返回“C:\Users\Travis\Desktop\test.c”,这是存储我的源代码的绝对路径,但不是我正在搜索的文件。
我的确切代码是:
import os
Files={}#Dictionary that will hold file names and absolute paths
root=os.getcwd()#Finds starting point
for root, dirs, files in os.walk(root):
for file in files:
if file.endswith('.c'):#Look for files that end in .c
Files[file]=os.path.abspath(file)
关于它为什么会这样做以及如何解决它的任何提示或建议?提前致谢!