Python文件路径操作

print(os.environ.get('HOME')) # 打印`HOME`这个环境变量

/Users/<>

file_path = os.environ.get('HOME') + '/text.txt' # 拼贴文件路经,注意不要漏掉`/`
print(file_path)

/Users/<>/text.txt

file_path = os.path.join(os.environ.get('HOME'), 'test.txt') # 使用`os.path.join`也可以拼贴文件路经,不用担心漏掉`/`的问题
print (file_path)
print(os.path.basename('/tmp/test.txt')) # 打印 `basename`

test.txt

print(os.path.dirname('/tmp/test.txt')) # 打印`dirname`目录

/tmp

print(os.path.split('/tmp/test.txt')) # 把目录和文件分开打印出来

('/tmp', 'test.txt')

print(os.path.exists('/tmp/test.txt')) # 判断文件是否存在

False

print(os.path.isdir('/tmp/test.txt')) # 判断是否为_文件夹_
print(os.path.isfile('/tmp/test.txt')) # 判断是否为_文件_
print(os.path.splitext('/tmp/test.txt')) # 把扩展名分开打印出来

('/tmp/test', '.txt')

print(dir(os.path)) # 打印`os.path`模块下的目录(也就是os.path的所有命令)
原文地址:https://www.cnblogs.com/yaos/p/7015822.html