python之os.path模块

1、简介

  os.path模块:常见的路径名操作。这个模块在路径名上实现了一些有用的功能。

2、方法

2.1、os.path.abspath(path)

  调用 os.path.abspath(path)将返回参数的绝对路径的字符串。这是将相对路径转换为绝对路径的简便方法。

import os
filepath = "Flask"
print(os.path.abspath(filepath))

  输出结果:

F:sharepythonFlask

2.2、os.path.basename(path)

  用 os.path.basename(path)将返回一个字符串,它包含 path 参数中最后一个斜杠之后的所有内容。

import os
filepath = "F:sharepython"
print(os.path.basename(filepath))

  输出结果:

python

2.3、os.path.dirname(path)

  调用 os.path.dirname(path)将返回一个字符串,它包含 path 参数中最后一个斜杠之前的所有内容。

import os
filepath = "F:sharepython"
print(os.path.dirname(filepath))

   输出结果:

F:share

2.4、os.path.exists(path)

  如果 path 参数所指的文件或文件夹存在, 调用 os.path.exists(path)将返回 True,否则返回 False。

import os
filepath = "F:sharepython"
print(os.path.exists(filepath))

  输出结果:

True

  

import os
filepath = "F:sharepythonhello"
print(os.path.exists(filepath))

  输出结果:

False

2.5、os.path.getsize(path)

  获取文件大小。

import os
filepath = "F:sharepythonstyle.css"
print(os.path.getsize(filepath))

  输出结果:

1561

2.6、os.path.isabs(path)

  调用 os.path.isabs(path),如果参数是一个绝对路径,就返回 True,如果参数是一个相对路径,就返回 False。

import os
filepath = "F:sharepythonstyle.css"
print(os.path.isabs(filepath))

  输出结果:

True

  

import os
filepath = "style.css"
print(os.path.isabs(filepath))

  输出结果:

False

2.7、os.path.isfile(path)

   如果 path 参数存在,并且是一个文件,调用 os.path.isfile(path)将返回 True,否则返回 False。

import os
filepath = "style.css"
print(os.path.isfile(filepath))

  输出结果:

True

  

import os
filepath = "F:sharepython"
print(os.path.isfile(filepath))

  输出结果:

False

2.8、os.path.isdir(path)

  如果 path 参数存在,并且是一个文件夹, 调用 os.path.isdir(path)将返回 True,否则返回 False。

import os
filepath = "F:sharepython"
print(os.path.isdir(filepath))

  输出结果:

True
import os
filepath = "style.css"
print(os.path.isdir(filepath))

  输出结果:

False

2.9、os.path.join(path, *paths)

  合成文件路径。

import os
filepath = "F:sharepython"
print(os.path.join(filepath, "hello","ok.c"))

  输出结果:

F:sharepythonhellook.c

2.10、os.path.split(path)

  分割一个路径为目标名称和基本名称。

  

import os
filepath = "F:sharepythonFlaskSamplemanager.py"
os.path.split(filepath)

  输出结果:

('F:\share\python\Flask\Sample', 'manager.py')

2.11、os.path.relpath(path, start=os.curdir)

  用 os.path.relpath(path, start)将返回从 start 路径到 path 的相对路径的字符串。如果没有提供 start,就使用当前工作目录作为开始路径。

import os
print(os.path.relpath("F:share", "F:workspacehello"))

  输出结果:

....share
原文地址:https://www.cnblogs.com/bad-robot/p/9733939.html