Python 3:路径处理


#Python#


os.getcwd() 获取当前工作目录

getcwd 用于获取当前工作目录的绝对路径:

import os
print(os.getcwd())

将上面的代码保存在~/Desktop/py-project/os_path.py文件中,在不同的目录下执行该代码,结果是不同的:

$ cd ~/Desktop/py-project/
$ python3 os_path.py
/Users/letian/Desktop/py-project
$ cd /Users/letian/Downloads
$ python3 ~/Desktop/py-project/os_path.py
/Users/letian/Downloads

系统路径分隔符 os.path.seq

import os
print(os.path.sep)

在 Linux/macOS 上输出 /。在Windows上输出\

获取当前Python文件所在位置

import os
print(os.path.realpath(__file__))

输出:

/Users/letian/Desktop/py-project/os_path.py

获取路径中的目录和文件名

示例1:

import os

current_file_path = os.path.realpath(__file__)
print(os.path.dirname(current_file_path))
print(os.path.basename(current_file_path))
print(os.path.split(current_file_path))

输出:

/Users/letian/Desktop/py-project
os_path.py
('/Users/letian/Desktop/py-project', 'os_path.py')

示例2:

import os

print(os.path.dirname('/note/'))
print(os.path.basename('/note/'))

print(os.path.dirname('/note'))
print(os.path.basename('/note'))

print(os.path.dirname('./note'))
print(os.path.basename('./note'))

输出:

/note

/
note
.
note

获取指定路径的绝对路径

import os

print(os.path.abspath('/note/'))
print(os.path.abspath('/note/..'))
print(os.path.abspath('./note/'))
print(os.path.abspath('os_path.py'))

输出:

/note
/
/Users/letian/Desktop/py-project/note
/Users/letian/Desktop/py-project/os_path.py

组装路径

import os

print(os.path.join('/note/text.txt'))
print(os.path.join('/note/', 'test.txt'))
print(os.path.join('/note', 'test.txt'))
print(os.path.join('/note', 'test.txt', '..'))

输出:

/note/text.txt
/note/test.txt
/note/test.txt
/note/test.txt/..

判断是不是绝对路径

import os

print(os.path.isabs('.'))
print(os.path.isabs('os_path.py'))

print(os.path.isabs('/'))
print(os.path.isabs('/usr'))

输出:

False
False
True
True

获取一个路径相对于另外一个路径的相对路径

import os

print(os.path.relpath('/note/test.txt', '/'))
print(os.path.relpath('/note/test.txt', '/note'))
print(os.path.relpath('/note/test.txt', '/usr'))

输出:

note/test.txt
test.txt
../note/test.txt

获取路径在系统上是否存在

import os

print(os.path.exists('/note/test.txt'))
print(os.path.exists('/note/'))
print(os.path.exists('test.txt'))

print(os.path.exists('/usr/'))
print(os.path.exists('/usr/bin/python'))
print(os.path.exists('os_path.py'))
print(os.path.exists('./os_path.py'))

输出:

False
False
False
True
True
True
True

判断路径在系统上是不是目录

如果不存在或者不是目录,则返回 False 。

import os

print(os.path.isdir('/usr/'))

print(os.path.isdir('/note/test.txt'))
print(os.path.isdir('/note/'))
print(os.path.isdir('test.txt'))
print(os.path.isdir('/usr/bin/python'))
print(os.path.isdir('os_path.py'))
print(os.path.isdir('./os_path.py'))

输出:

True
False
False
False
False
False
False

判断路径在系统上是不是文件

如果不存在或者不是文件,则返回 False 。

import os

print(os.path.isfile('/usr/'))
print(os.path.isfile('/note/test.txt'))
print(os.path.isfile('/note/'))
print(os.path.isfile('test.txt'))

print(os.path.isfile('/usr/bin/python'))
print(os.path.isfile('os_path.py'))
print(os.path.isfile('./os_path.py'))

( 本文完 )