os.path.join() 方法

Python中的OS模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。os.path模块是 Python 中 OS 模块的子模块,用于常见的路径名操作。
Python 中的os.path.join()方法智能地连接一个或多个路径组件。此方法将各个路径组件与除最后一个路径组件之外的每个非空部分后面的一个目录分隔符(“/”)连接起来。如果要连接的最后一个路径组件为空,则在末尾放置一个目录分隔符(“/”)。
如果路径组件表示绝对路径,则所有先前连接的组件都将被丢弃,并从绝对路径组件继续连接。``

语法: os.path.join(path, *paths)
参数:
path:表示文件系统路径的类路径对象。
path:表示文件系统路径的类路径对象。它表示要连接的路径组件。
类似路径的对象是表示路径的字符串或字节对象。
注意: Python 中函数定义中的特殊语法
args(此处为 *paths)用于将可变数量的参数传递给函数。
返回类型:此方法返回一个表示串联路径组件的字符串。
`python

Python program to explain os.path.join() method

importing os module

import os

Path

path = “/home”

Join various path components

print(os.path.join(path, “User/Desktop”, “file.txt”))

Path

path = “User/Documents”

Join various path components

print(os.path.join(path, “/home”, “file.txt”))

In above example ‘/home’

represents an absolute path

so all previous components i.e User / Documents

are thrown away and joining continues

from the absolute path component i.e / home.

Path

path = “/User”

Join various path components

print(os.path.join(path, “Downloads”, “file.txt”, “/home”))

In above example ‘/User’ and ‘/home’

both represents an absolute path

but ‘/home’ is the last value

so all previous components before ‘/home’

will be discarded and joining will

continue from ‘/home’

Path

path = “/home”

Join various path components

print(os.path.join(path, “User/Public/”, “Documents”, “”))

In above example the last

path component is empty

so a directory separator (‘/’)

will be put at the end

along with the concatenated value


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值