Skip to main content
 首页 » 编程设计

python之为什么os.path.abspath()返回的是cwd+file的路径

2025年05月04日15lhb25

如果我有这样的结构:

root/ 
-- group1/ 
---- names/ 
---- places/ 
------ foo.zip 

为什么当我调用 os.path.abspath('foo.zip') 时,我得到了 Python 脚本所在的文件路径加上 foo.zip?

看起来像:H:\Program\Scripts\foo.zip

需要是:H:\Progran\Groups\group1\names\places\foo.zip

这是导致问题的函数的代码:

def unzip(in_dir): 
    # in_dir is places passed to unzip() 
    files = [f for f in os.listdir(os.path.abspath(in_dir)) if f.endswith('.zip')] 
    for zip in files: 
        # This prints the 'looks like' path above 
        print os.path.abspath(zip) 

不应该 print os.path.abspath(zip) 给我在 os.listdir(os.path.abspath(in_dir) )?

请您参考如下方法:

Why does os.path.abspath() return the path of cwd+file?

因为字面意思就是 abspath 应该做的:

os.path.abspath(path)

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

(强调我的)