笔者:风起怨江南 出处:https://blog.csdn.net/JackMengJin 笔者原创,文章转载需注明,如果喜欢请点赞+关注,感谢支持!
导读:内置模块os模块和os.path模块相关内容的讲解。
目录
os模块的常用操作
1.os模块介绍
os是操作系统的意思,而os模块的作用就是处理和操作系统相关的操作,比如处理文件和目录这些经常做的操作。
os模块是内置函数,所以导入方式直接import + 模块的方式即可:
import os
os模块源码的注释:
r"""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模块同时适用于Linux系统(posix)和Windows系统(nt)。
通过os.可以看到os模块支持很多功能:
比如第一个os.name操作,表示显示当前使用的系统名。
Windows系统:
print(os.name)
nt
Linux系统:
print(os.name)
posix
而在Pyhton中文件路径相关的操作可以用os模块的子模块os.path模块去实现操作,在python3.6以上也可以用pathlib模块去实现文件操作,在学完类和对象后再去讲解pathlib模块的相关内容。
本文的重点还是对os.path模块的研究。
2.绝对路径和相对路径
在学习os.path操作之前,先要搞清楚绝对路径和相对路径这两个概念:
绝对路径:绝对路径是指目录下的绝对位置,直接到达目标位置,通常是从盘符开始的路径。
完整的描述文件位置的路径就是绝对路径,以web站点根目录为参考基础的目录路径。
绝对路径名的指定是从树型目录结构顶部的根目录开始到某个目录或文件的路径,由一系列连续的目录组成,中间用斜线分隔,直到要指定的目录或文件,路径中的最后一个名称即为要指向的目录或文件。
之所以称为绝对,意指当所有网页引用同一个文件时,所使用的路径都是一样的。
os.path.abspath(__file__)可以得到当前文件的绝对路径:
print(os.path.abspath(__file__))
E:\MyLife\博客\demo.py
E:就是盘符,而在Linux系统下从系统根目录开始,以“/”为起始:
/home/jack/demo/demo.py
而相对路径,顾名思义就是一个路径相对于另一个路径的说法。
相对路径就是指由这个文件所在的路径引起的跟其它文件(或文件夹)的路径关系。
通过用..表示为父目录。
比如在 E:\MyLife 目录下,E:\MyLife就是 E:\MyLife\博客 的父目录。
而在 E:\MyLife\博客 目录下的文件,直接\加相应目录即可。
比如说C盘demo文件夹下有两个文件1.txt和2.txt。
如果要以文件1.txt的视角说出文件2.txt的路径,那么它有两种表示方法: