Python中 os 模块详解

1. 概述

OS 模块提供了一种使用操作系统相关功能的便携方式。
如果您只想读取或写入文件,使用open()方法;
如果要操作路径,使用 os.path 模块;
如果要读取命令行中所有文件中的所有行 ,使用 fileinput 模块;
有关创建临时文件和目录的信息,使用 tempfile 模块;
有关高级文件和目录的处理,使用 shutil 模块。

下面对经常使用的功能进行介绍;

2. 介绍

2.1 获取当前路径及路径下的文件

os.getcwd():查看当前所在路径。
os.listdir(path): 列举目录下的所有文件。返回的是列表类型。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2019/3/27 10:39
# @Author  : Arrow and Bullet
# @FileName: os_.py
# @Software: PyCharm
# @Blog    :https://blog.csdn.net/qq_41800366
import os

cp = os.getcwd()  # 获取当前路径, 返回绝对路径
print(cp)  # C:\Users\Desktop\tensorflow\os
fileList = os.listdir(cp)  # 获取路径下的文件,以及文件夹
print(fileList)  # ['os_.py', 'sub', 'test.txt']
2.2 获取路径的绝对路径

os.path.abspath(path): 返回path的绝对路径

abspath1 = os.path.abspath(".")  # 返回当前路径的绝对路径
print(abspath1)  # C:\Users\Desktop\tensorflow\os
abspath2 = os.path.abspath("../")  # 返回上一层路径的绝对路径
print(abspath2)  # C:\Users\Desktop\tensorflow
2.3 查看路径的文件夹部分和文件名部分

os.path.split(path): 将路径分解为(文件夹,文件名),返回的是元组类型。可以看出,若路径字符串最后一个字符是,则只有文件夹部分有值;若路径字符串中均无,则只有文件名部分有值。若路径字符串有\,且不在最后,则文件夹和文件名均有值。且返回的文件夹的结果不包含.

os.path.join(path1,path2,…): 将path进行组合,若其中有绝对路径,则之前的path将被删除。

catalogue_and_file1 = os.path.split('D:\pythontest\ostest\Hello.py')
print(catalogue_and_file1)  # ('D:\\pythontest\\ostest', 'Hello.py')
catalogue_and_file2 = os.path.split('.')
print(catalogue_and_file2)  # ('', '.')
catalogue_and_file3 = os.path.split('D:\pythontest\ostest\\')
print(catalogue_and_file3)  # ('D:\\pythontest\\ostest', '')

path_join1 = os.path.join('D:\pythontest', 'ostest')
print(path_join1)  # D:\pythontest\ostest
path_join2 = os.path.join('D:\pythontest\ostest', 'hello.py')
print(path_join2)  # D:\pythontest\ostest\hello.py
path_join3 = os.path.join('D:\pythontest\\b', 'D:\pythontest\\a')
print(path_join3)  # D:\pythontest\a

os.path.dirname(path):返回path中的文件夹部分,结果不包含’’;
os.path.basename(path):返回path中的文件名。

os中还有十分多的功能,博主只给出了比较常用的几个功能。具体可以点击查看

  1. os 官方
  2. python之os模块

希望能够帮助到大家,有什么问题可以 直接评论即可,喜欢有用的话可以点个赞让更多的人看到,如果不够详细的话也可以说,我会及时回复的。

你可能感兴趣的:(Python)