Wal*_*acs 2 python dictionary absolute-path os.path
我在网站上阅读了很多链接,说要使用“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)
Run Code Online (Sandbox Code Playgroud)
关于为什么会这样做以及我如何解决它的任何提示或建议?提前致谢!
os.path.abspath()使相对路径绝对相对于当前工作目录,而不是文件的原始位置。路径只是一个字符串,Python 无法知道文件名的来源。
您需要自己提供目录。当您使用 时os.walk,每次迭代都会列出正在列出的目录(root在您的代码中)、子目录列表(只是它们的名称)和一个文件名列表(同样,只是它们的名称)。使用root连同文件名,使绝对路径:
Files={}
cwd = os.path.abspath(os.getcwd())
for root, dirs, files in os.walk(cwd):
for file in files:
if file.endswith('.c'):
Files[file] = os.path.join(root, os.path.abspath(file))
Run Code Online (Sandbox Code Playgroud)
请注意,您的代码仅记录每个唯一文件名的一个路径;如果您有foo/bar/baz.cand foo/spam/baz.c,则取决于操作系统列出两个路径之一获胜的bar和spam子目录的顺序。
您可能希望将路径收集到列表中:
Files={}
cwd = os.path.abspath(os.getcwd())
for root, dirs, files in os.walk(cwd):
for file in files:
if file.endswith('.c'):
full_path = os.path.join(root, os.path.abspath(file))
Files.setdefault(file, []).append(full_path)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3119 次 |
| 最近记录: |