前言
os模块:是对操作系统的调用,模拟对操作系统的指令
os 模块提供了一种使用操作系统相关功能的便携方式。如果您只想读取或写入文件,使用 open() 方法;如果要操作路径,使用 os.path 模块;如果要读取命令行中所有文件中的所有行 ,使用 fileinput 模块;有关创建临时文件和目录的信息,使用 tempfile 模块;有关高级文件和目录的处理,使用 shutil 模块。
下面对经常使用的功能进行介绍;
全解
1.获取当前路径及路径下的文件
os.getcwd():查看当前所在路径。
os.listdir(path): 列举目录下的所有文件。返回的是列表类型。
import os
cp = os.getcwd() # 获取当前路径, 返回绝对路径
print(cp) # C:\Users\Desktop\w3cschool\os
fileList = os.listdir(cp) # 获取路径下的文件,以及文件夹
print(fileList) # ['os_.py', 'sub', 'test.txt']
2.获取路径的绝对路径
os.path.abspath(path): 返回path的绝对路径
abspath1 = os.path.abspath(".") # 返回当前路径的绝对路径
print(abspath1) # C:\Users\Desktop\w3cschool\os
abspath2 = os.path.abspath("../") # 返回上一层