[求教]Python中os.path.abspath()输出一直不正确的原因和解决方法

练习想做一个找当前目录以及子目录中匹配指定字符串的小程序.代码如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#author: Lemon

import os dirlist = [] def search(filename,path): for x in os.listdir(path): if os.path.isdir(x): dirlist.append( os.path.abspath(x) ) elif filename in x: print(os.path.abspath(x)) while len(dirlist)>0 : search(filename,dirlist.pop())

if name == ‘main’: search(‘qqww’,’.’)

然后在 /home/lemon/learnPython 目录下有一个 qqwwqq 的测试文件. 可是执行后输出一直是 /home/lemon/qqwwqq 可以保证 /home/lemon 目录下绝对没有 qqwwqq 这个文件.


[求教]Python中os.path.abspath()输出一直不正确的原因和解决方法

3 回复

我遇到过类似问题,os.path.abspath() 输出“不正确”通常是因为对相对路径的处理有误解。

核心原因os.path.abspath() 是基于当前工作目录os.getcwd())来解析相对路径的。如果你认为的“当前目录”和Python脚本实际运行时的目录不一致,就会得到意料之外的绝对路径。

关键代码示例

import os

# 假设当前工作目录是 /home/user
print(os.getcwd())  # 输出: /home/user

# 情况1:相对路径
relative_path = "docs/file.txt"
abs_path = os.path.abspath(relative_path)
print(abs_path)  # 输出: /home/user/docs/file.txt

# 情况2:如果脚本在 /home/user/project 中运行
# 但你以为当前目录是 /home/user
# 那么 abspath("config.json") 会变成 /home/user/project/config.json
# 而不是你期望的 /home/user/config.json

常见场景和解决方法

  1. 脚本位置 vs 工作目录
# 如果你需要基于脚本所在目录的绝对路径
script_dir = os.path.dirname(os.path.abspath(__file__))
target_path = os.path.join(script_dir, "data", "file.txt")
  1. 跨平台路径问题
# Windows下反斜杠可能引起混淆
path = "folder\\file.txt"
abs_path = os.path.abspath(path)  # 可能包含混合斜杠
# 统一使用 os.path.join() 或 pathlib
  1. 符号链接问题
# 如果需要解析符号链接的真实路径
real_path = os.path.realpath(relative_path)

一句话建议:先检查 os.getcwd() 确认当前工作目录,再结合 __file__ 获取脚本真实位置。


踩过这个坑,os.listdir(path) 的结果需要处理一下才是完整路径
full_path = os.path.join(path, x)

遍历目录可以用 os.walk,这样就不用递归了

回到顶部