Python中的os.path模块提供了一系列用于处理路径的函数,可以帮助我们方便地操作文件路径。下面我们将介绍一些常见的函数及其用法。
os.path.join():用于连接两个或多个路径名组件,返回连接后的路径名。import os path1 = 'C:/Users' path2 = 'John' path3 = 'Documents' full_path = os.path.join(path1, path2, path3) print(full_path) # Output: C:/Users/John/Documentsos.path.exists():用于检查文件或目录是否存在,如果存在则返回True,否则返回False。
import os
path = 'C:/Users/John/Documents'
if os.path.exists(path):
print('File or directory exists')
else:
print('File or directory does not exist')
- os.path.isfile():用于检查是否为文件,如果是则返回True,否则返回False。 ```python import os path = 'C:/Users/John/Documents/file.txt' if os.path.isfile(path): print('File exists') else: print('File does not exist')</code></pre> <ul> <li>os.path.isdir():用于检查是否为目录,如果是则返回True,否则返回False。 <pre><code class="language-python"></code></pre></li> </ul> <p>import os</p> <p>path = 'C:/Users/John/Documents'</p> <p>if os.path.isdir(path): print('Directory exists') else: print('Directory does not exist')</p> <pre><code> - os.path.basename():用于获取文件名或目录名,返回路径中最后一个组件。 ```python import os path = 'C:/Users/John/Documents/file.txt' print(os.path.basename(path)) # Output: file.txt
os.path.dirname():用于获取文件所在目录的路径,返回路径中除最后一个组件外的所有内容。
Python技术站热门推荐:
PDF电子发票识别软件,一键识别电子发票并导入到Excel中!
10大顶级数据挖掘软件!
人工智能的十大作用!
import os path = 'C:/Users/John/Documents/file.txt' print(os.path.dirname(path)) # Output: C:/Users/John/Documentsos.path.splitext():用于将文件名和扩展名分开,返回一个元组。
import os path = 'C:/Users/John/Documents/file.txt' name, ext = os.path.splitext(path) print(name) # Output: C:/Users/John/Documents/file print(ext) # Output: .txt
以上7种是os.path模块中比较常见的函数,它们能够帮助我们更方便地处理文件路径。除此之外,os.path还有以下函数:
os.path.abspath(path):返回给定路径的绝对路径,即将相对路径转化为绝对路径。 os.path.normpath(path):该函数规范化路径,即去掉路径中的冗余部分,例如双斜杠“//”,单个点“.”等等。 os.path.split(path):该函数将路径分解为两部分,分别是目录和文件名,返回一个元组。 os.path.splitext(path):该函数将路径分解为文件名和扩展名,返回一个元组。 os.path.join(path1[, path2[, ...]]):该函数将多个路径组合成一个完整的路径。 os.path.commonprefix(list):该函数返回列表中所有路径的公共前缀,即最长的公共路径。需要注意的是,操作文件路径时应尽量使用os.path模块中的函数,而不是手动拼接路径,以避免出现错误。
查看更多关于Python os.path模块的7种常用函数的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did254539