绝对路径和相对路径是文件系统中用来指定文件位置的两种方式。
1. 绝对路径 (Absolute Path)
- 定义:绝对路径是从文件系统的根目录开始,完整的指定文件或目录的位置。无论当前工作目录在哪,绝对路径始终指向同一个位置。
- 示例:在Windows中,绝对路径可能是
C:\Users\Alice\Documents\file.txt;在Linux中,它可能是/home/alice/documents/file.txt。
2. 相对路径 (Relative Path)
- 定义:相对路径是相对于当前工作目录的文件或目录位置。它不以根目录为起点,而是根据当前文件位置来推断。
- 示例:如果当前目录是
/home/alice/,那么documents/file.txt就是一个相对路径,指向/home/alice/documents/file.txt。
代码示例
假设当前工作目录为 /home/alice/,且有以下文件和目录:
/home/alice/
├── documents/
│ ├── file1.txt
│ └── file2.txt
└── images/
└── image1.jpg
- 绝对路径示例:
file1.txt的绝对路径是/home/alice/documents/file1.txtimage1.jpg的绝对路径是/home/alice/images/image1.jpg- 相对路径示例:
- 从
/home/alice/目录,可以通过相对路径访问文件:documents/file1.txt - 如果当前目录是
/home/alice/documents/,要访问file2.txt,则相对路径为file2.txt
文件列表
/home/alice/
├── documents/
│ ├── file1.txt
│ └── file2.txt
└── images/
└── image1.jpg
示例代码:
import os
# 假设当前工作目录为 /home/alice/
current_directory = '/home/alice/'
# 绝对路径
absolute_path_file1 = os.path.join(current_directory, 'documents', 'file1.txt')
absolute_path_image1 = os.path.join(current_directory, 'images', 'image1.jpg')
print("绝对路径 file1.txt:", absolute_path_file1)
print("绝对路径 image1.jpg:", absolute_path_image1)
# 相对路径
relative_path_file1 = os.path.join('documents', 'file1.txt')
relative_path_image1 = os.path.join('images', 'image1.jpg')
print("相对路径 file1.txt:", relative_path_file1)
print("相对路径 image1.jpg:", relative_path_image1)
输出:
绝对路径 file1.txt: /home/alice/documents/file1.txt
绝对路径 image1.jpg: /home/alice/images/image1.jpg
相对路径 file1.txt: documents/file1.txt
相对路径 image1.jpg: images/image1.jpg
总结
- 绝对路径:从根目录开始的完整路径,始终唯一。
- 相对路径:相对于当前目录的路径,可能会根据当前工作目录的不同而变化。


Comments NOTHING