os模块
os模块简介
os模块是我们接触python可能最常用的一个内置模块。os作者是认为是operation system.既然是操作系统自然我们所有在windows/unix系列操作系统上的操作都可以通过os模块去替代。
首先, 附上os模块的文档说明.
import os
print(os.__doc__)
"""
OS routines for NT or Posix depending on what system we're on.
This exports:
- all functions from posix or nt, e.g. unlink, stat, etc.
- os.path is either posixpath or ntpath
- os.name is either 'posix' or 'nt'
- os.curdir is a string representing the current directory (always '.')
- os.pardir is a string representing the parent directory (always '..')
- os.sep is the (or a most common) pathname separator ('/' or '\\')
- os.extsep is the extension separator (always '.')
- os.altsep is the alternate pathname separator (None or '/')
- os.pathsep is the component separator used in $PATH etc
- os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
- os.defpath is the default search path for executables
- os.devnull is the file path of the null device ('/dev/null', etc.)
Programs that import and use 'os' stand a better chance of being
portable between different platforms. Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
"""
os模块操作路径:os.path
abspath 返回路径的绝对值.
Return the absolute version of a path.
import os
os.path.abspath(__file__)
# c:\Users\Admin\Desktop\简书.py
dirname 返回一个路径的父级目录
Returns the directory component of a pathname
os.path.dirname(__file__)
# c:\Users\Admin\Desktop
basename 返回路径的最后一个组件
Returns the final component of a pathname
os.path.dirname(__file__)
# 简书.py
exists 判断文件是否存在
Test whether a path exists. Returns False for broken symbolic links
os.path.exists(__file__)
# True