京公网安备 11010802034615号
经营许可证编号:京B2-20210330
作者:小伍哥
来源:AI入门学习
os,语义操作系统,所以该模块就是操作系统相关的功能了,用于处理文件和目录这些我们日常手动需要做的操作,比如新建文件夹、获取文件列表、删除某个文件、获取文件大小、重命名文件、获取文件修改时间等,该模块就包含了大量的操作系统操作函数,精选常用的进行解析,希望对大家有所帮助。
os下面有很多函数,调用方式一般为os.name,其中比较特殊的是Path,Path模块是OS的一个子模块,下面又有很多的函数,调用方式一般为os.path.isfile。刚接触的可能不大明白,需要注意下。
#加载
import os
#查看os下的函数
print(dir(os))
#查看os.path下的函数
print(dir(os.path))
01、os.name()
描述:显示当前使用的平台,'nt'表示Windows,'posix' 表示Linux
语法:os.name
os.name
'nt'
02、os.getcwd()
描述:返回当前进程的工作目录。
语法:os.getcwd()
os.getcwd()
'C:\\Users\\wuzhengxiang'
03、os.chdir()
描述:改变当前工作目录到指定的路径。
语法:os.chdir(path)
#查看当前目录os.getcwd()
'C:\\Users\\wuzhengxiang'#重新设置当前工作空间
os.chdir('C:/Users/wuzhengxiang/Desktop/股票数据分析')
#再次查看当前目录,已经变成新的了
os.getcwd()
'C:\\Users\\wuzhengxiang\\Desktop\\股票数据分析'
04、os.makedirs()
描述:方法用于递归创建目录。像 mkdir(), 但创建的所有intermediate-level文件夹需要包含子目录。
语法:os.makedirs(path, mode=0o777)
os.makedirs('C:/Users/wuzhengxiang/Desktop/股票数据分析/1122', mode=0o777)
05、os.mkdir()
描述:以数字权限模式创建目录。默认的模式为 0777 (八进制)。
语法:os.mkdir(path[, mode])
#创建新的目2233
os.mkdir('C:/Users/wuzhengxiang/Desktop/股票数据分析/2233', mode=0777 )
06、os.listdir()
描述:列出目录下的所有文件和文件夹
语法:os.listdir(path)
os.listdir('C:/Users/wuzhengxiang/Desktop/股票数据分析')
['ETF研究.py', 'foo.txt', 'pi.txt', 'render.html']
os.listdir('.')
['ETF研究.py', 'foo.txt', 'pi.txt', 'render.html']
07、os.remove()
描述:用于删除指定路径的文件。如果指定的路径是一个目录,将抛出OSError。
语法:os.remove(path)
os.remove('C:/Users/zhengxiang.wzx/Desktop/timg.jpg')
08、os.rename()
描述:命名文件或目录,能对相应的文件进行重命名
语法:os.rename(src, dst)
参数
#空间设置
data_path = 'C:/Users/zhengxiang.wzx/Desktop/微博情绪识别'
os.chdir(data_path)#设置工作空间
os.getcwd()
'C:\\Users\\zhengxiang.wzx\\Desktop\\微博情绪识别'
os.rename("图片下载.py","图片下载1.py")
09、os.renames()
描述:用于递归重命名目录或文件。类似rename()。既可以重命名文件, 也可以重命名文件的上级目录名
语法:os.renames(old, new)
参数:
os.chdir('C:/Users/wuzhengxiang/Desktop/Python知识点总结')
os.getcwd()
#文件夹和文件同时命名
os.renames("test/Python 63个内置函数详解.py","test2/内置函数详解.py")
os.listdir()
['kaggle',
'test2',
'股票分析',
'课程资源'
10、os.linesep()
描述:当前平台用于分隔(或终止)行的字符串。它可以是单个字符,如 POSIX 上是 '\n',也可以是多个字符,如 Windows 上是 '\r\n'。在写入以文本模式(默认模式)打开的文件时,请不要使用 os.linesep 作为行终止符,请在所有平台上都使用一个 '\n' 代替。
语法:os.linesep
os.linesep
'\r\n'
11、os.pathsep()
描述:操作系统通常用于分隔搜索路径(如 PATH)中不同部分的字符,如 POSIX 上是 ':',Windows 上是 ';'。在 os.path 中也可用。
语法:os.pathsep
os.pathsep
';'
12、os.close()
描述:关闭指定的文件描述符 fd
语法:os.close(fd)
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
os.write(fd, bytes("This is test", encoding = "utf8"))
os.close( fd )
13、os.stat()
描述:获取文件或者目录信息
语法:os.stat(path)
os.stat('C:/Users/wuzhengxiang/Desktop/股票数据分析\\pi.txt')
os.stat_result(st_mode=33206, st_ino=22236523160361562, st_dev=2419217970, st_nlink=1
, st_uid=0, st_gid=0, st_size=53, st_atime=1589638199, st_mtime=1589638199, st_ctime=1581868007)
14、os.sep()
描述:显示当前平台下路径分隔符,在 POSIX 上是 '/',在 Windows 上是是 '\\'
语法:os.sep
os.sep'
\\'
15、os.path.abspath()
描述:返回文件的绝对路径
语法:os.path.abspath(path)
#Excel文件
os.path.abspath('all_data.xlsx')
'C:\\Users\\zhengxiang.wzx\\all_data.xlsx'
#图片文件
os.path.abspath('IMG_7358.JPG')
'C:\\Users\\zhengxiang.wzx\\IMG_7358.JPG'
16、os.path.basename()
描述:返回文件名,纯粹字符串处理逻辑,路径错误也可以
语法:os.path.basename(path)
os.path.basename('C:\\Users\\zhengxiang.wzx\\all_data.xlsx')
'all_data.xlsx'
17、os.path.commonprefix()
描述:返回list(多个路径)中,所有path共有的最长的路径
语法:os.path.commonprefix(list)
os.path.commonprefix(['http://c.biancheng.net/python/aaa', 'http://c.biancheng.net/shell/'])'http://c.biancheng.net/'os.path.commonprefix(['http://bianc/python/aaa', 'http://c.biancheng.net/shell/'])'http://'
18、os.path.dirname()
描述:返回文件路径
语法:os.path.dirname(path)
os.path.dirname('C://my_file.txt')
'C://'
os.path.dirname('C://python//my_file.txt')
'C://python'
19、os.path.exists()
描述:如果路径 path 存在,返回 True;如果路径 path 不存在,返回 False。
语法:os.path.exists(path)
os.path.exists('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
True
os.path.exists('C:/Users/wuzhengxiang/Desktop/股票数据分析/')
True
os.path.exists('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi_01.txt')
Fals
20、os.path.lexists()
描述:路径存在则返回True,路径损坏也返回True, 不存在,返回 False。
语法:os.path.lexists
os.path.lexists('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
True
os.path.lexists('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi_01.txt')
False
21、os.path.expanduser()
描述:把path中包含的"~"和"~user"转换成用户目录
语法:os.path.expanduser(path)
os.path.expanduser('~/wuzhengxiang/Desktop/股票数据分析/')
'C:\\Users\\wuzhengxiang/wuzhengxiang/Desktop/股票数据分析/'
22、os.path.expandvars()
描述:根据环境变量的值替换path中包含的"$name"和"${name}"
语法:os.path.expandvars(path)
os.environ['KITTIPATH'] = 'D:/thunder'
path = '$KITTIPATH/train/2011_09_26_drive_0001_sync/proj_depth/velodyne_raw/image_02/0000000013.png'
os.path.expandvars(path)
'D:/thunder/train/2011_09_26_drive_0001_sync/proj_depth/velodyne_raw/image_02/0000000013.png'
23、os.path.getatime()
描述:返回最近访问时间(浮点型秒数),从新纪元到访问时的秒数。
语法:os.path.getatime(path)
os.path.getatime('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
1589638199.1343248
24、os.path.getmtime()
描述:返回最近文件修改时间,从新纪元到访问时的秒数。
语法:os.path.getmtime(path)
os.path.getmtime('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
1583069050.8148942
25、os.path.getctime()
描述:返回文件 path 创建时间,从新纪元到访问时的秒数。
语法:os.path.getctime(path)
os.path.getctime('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
1581868007.6123319
26、os.path.getsize()
描述:返回文件大小,如果文件不存在就返回错误
语法:os.path.getsize(path)
os.path.getsize('C:/Users/wuzhengxiang/Desktop/股票数据分析/test.gif')
1128677
27、os.path.isabs()
描述:判断是否为绝对路径,也就是说在WIndow系统下,如果输入的字符串以" / "开头,os.path.isabs()就会返回True
语法:os.path.isabs(path)
os.path.isabs('D:/thunder')
True
os.path.isabs('D:\thunder')
False
os.path.isabs('D:\\thunder')
True
28、os.path.isfile()
描述:判断路径是否为文件
语法:os.path.isfile(path)
#文件不存在 返回False
os.path.isfile("C:/Users/wuzhengxiang/Desktop/股票数据分析/pi_01.txt")
False
os.path.isfile("C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt")
True#不是文件 返回Falseo
s.path.isfile("C:/Users/wuzhengxiang/Desktop/股票数据分析/")
False
29、os.path.isdir()
描述:判断路径是否为目录
语法:os.path.isdir(path)
os.path.isdir('C:/Users/wuzhengxiang/Desktop/股票数据分析')
True
os.path.isdir('C:/Users/wuzhengxiang/Desktop/股票数据分析1')
False
os.path.isdir('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
False
30、os.path.join()
描述:把目录和文件名合成一个路径,1.如果各组件名首字母不包含’/’,则函数会自动加上,2.如果有一个组件是一个绝对路径,则在它之前的所有组件均会被舍弃,3.如果最后一个组件为空,则生成的路径以一个’/’分隔符结尾
语法:os.path.join(path1[, path2[, ...]])
os.path.join('C:/Users','wuzhengxiang/Desktop/','股票数据分析')
'C:/Users\\wuzhengxiang/Desktop/股票数据分析'
Path1 = 'home'
Path2 = 'develop'
Path3 = 'code'
Path10 = Path1 + Path2 + Path3
Path20 = os.path.join(Path1,Path2,Path3)
print ('Path10 = ',Path10)
print ('Path20 = ',Path20)
Path10 = homedevelopcode
Path20 = home\develop\code
31、os.path.normcase()
描述:转换path的大小写和斜杠
语法:os.path.normcase(path)
os.path.normcase('D:\Python\test\data.txt')
'd:\\python\test\\data.txt'
os.path.normcase('c:/WINDOWS\\system64\\')
'c:\\windows\\system64\\'
32、os.path.normpath()
描述:规范path字符串形式
语法:os.path.normpath(path)
os.path.normpath('c://windows\\System32\\../Temp/')
'c:\\windows\\Temp'
33、os.path.realpath()
描述:返回path的真实路径
语法:os.path.realpath(path)
os.path.relpath('C:\\Users\\Administrat\\代码TRY\\test.ipynb', '代码TRY')
'..\\..\\..\\..\\Administrat\\代码TRY\\test.ipynb'
34、os.path.relpath()
描述:返回从当前目录或 start 目录(可选)到达 path 之间要经过的相对路径。这仅仅是对路径的计算,不会访问文件系统来确认 path 或 start 的存在性或属性。
语法:os.path.relpath(path[, start])
os.path.relpath('C:/Users/wuzhengxiang/Desktop/股票数据分析\\test.gif')
'test.gif'
35、os.path.samefile( )
描述:判断目录或文件是否相同
语法:os.path.samefile(path1, path2)
os.path.samefile('C:\\Users', 'C:\\Users')True
os.path.samefile('C:\\Users', 'C:/Users')True
os.path.samefile('C:\\Users', 'C:/Users/wuzhengxiang')False
36、os.path.split()
描述:把路径分割成 dirname 和 basename,返回一个元组
语法:os.path.split(path)
os.path.split('D:\Python\test\data.txt')
('D:\\Python\test', 'data.txt')
37、os.path.splitdrive()
37、os.path.splitdrive()
描述:一般用在 windows 下,返回驱动器名和路径组成的元组
语法:os.path.splitdrive(path)
os.path.splitdrive('C:/Users/zhengxiang.wzx/IMG_7358.JPG')
('C:', '/Users/zhengxiang.wzx/IMG_7358.JPG')
38、os.path.splitext()
描述:分割路径,返回路径名和文件扩展名的元组
语法:os.path.splitext(path)
os.path.splitext('C:/Users/zhengxiang.wzx/IMG_7358.JPG')
('C:/Users/zhengxiang.wzx/IMG_7358', '.JPG')
39、os.path.walk()
描述:遍历path,进入每个目录都调用visit函数,visit函数必须有3个参数(arg, dirname, names),dirname表示当前目录的目录名,names代表当前目录下的所有文件名,args则为walk的第三个参数
语法:os.path.walk(path, visit, arg)
list(os.walk(abs_cur_dir))
[('C:/Users/wuzhengxiang/Desktop/股票数据分析',
['1122'],
['ETF研究.py', 'foo.txt', 'pi.txt', 'render.html', 'test.gif']),
('C:/Users/wuzhengxiang/Desktop/股票数据分析\\1122', [], [])]
#穷举遍历一个文件夹里面的所有文件,并获取文件的目录名
abs_cur_dir ='C:/Users/wuzhengxiang/Desktop/股票数据分析'
file_url=[]
for dirs,folders,files in os.walk(abs_cur_dir):
for i in files:
file_url.append(os.path.join(dirs,i))
file_url
['C:/Users/wuzhengxiang/Desktop/股票数据分析\\ETF研究.py',
'C:/Users/wuzhengxiang/Desktop/股票数据分析\\foo.txt',
'C:/Users/wuzhengxiang/Desktop/股票数据分析\\pi.txt',
'C:/Users/wuzhengxiang/Desktop/股票数据分析\\render.html',
'C:/Users/wuzhengxiang/Desktop/股票数据分析\\test.gif']
#pathlib也能实现类似的
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
在Python数据分析中,Pandas库的DataFrame是最核心、最常用的结构化数据表对象,类似于Excel的二维表格,具备规整的行列结构、字 ...
2026-09-07在数据分析、经营复盘、业绩预测与经济统计工作中,平均增速(平均增长率)是衡量数据长期变化趋势、业务发展快慢的核心指标。不 ...
2026-09-07 很多数据分析师精通Excel单元格操作,但当被问到“表结构数据的基本处理单位是什么”“字段和记录的本质区别”“为什么表结 ...
2026-09-07随着大数据技术的快速发展,商业竞争逐步从传统的经验式经营转变为数据驱动的精细化运营。海量的用户行为数据、交易数据、运营数 ...
2026-09-04CDA数据分析师 出品 作者:李诗怡 1. 波士顿矩阵(BCG Matrix) 定义: BCG于1970年提出的业务组合分析工具,以"市场增长率"(纵 ...
2026-09-04 数据分析师八成以上的时间在和数据表格打交道,但许多人拿到Excel后习惯性地先算、先分析,结果回头发现漏了一列关键数据, ...
2026-09-04数据透视表是Excel与Power BI中最核心的数据分析工具,具备快速汇总、维度拆分、动态筛选的能力,可高效完成数据归类与统计展示 ...
2026-09-03在Power BI数据分析可视化场景中,堆积柱状图+折线图是最常用的复合图表组合。堆积柱状图适合展示各细分维度当期数值、结构占比 ...
2026-09-03 很多数据分析师每天与Excel打交道,但当被问到“表格结构数据的基本处理单位是什么”“数据类型误判会引发哪些分析错误”“ ...
2026-09-03CDA数据分析师 出品 作者:李诗怡 一、8个核心数据清洗函数 1. TRIM:一键清除多余空格(最常用) 作用:仅保留文本中"单词/字 ...
2026-09-02数据分析的核心并非单纯操作工具、整理报表或绘制图表,而是依靠科学的思维逻辑挖掘数据价值、解释业务现象、指导经营决策。在完 ...
2026-09-02在社会经济、产业研究、区域治理与大数据实证分析中,面板数据是最具研究价值的数据类型。面板数据同时包含截面维度与时间维度信 ...
2026-09-02 很多数据分析师能熟练计算均值、标准差,但当被问到“如何用一张图让业务方3秒内看懂核心结论”“面对不同数据类型该怎么选 ...
2026-09-02在数据驱动决策的体系中,数据分析按照分析目的可分为描述性分析、诊断性分析、预测性分析与指导性分析四大类型。其中,诊断性分 ...
2026-09-01网络请求是Python爬虫开发、接口测试、数据拉取的核心基础功能,Python生态中主要依靠 urllib 和 requests 两大库实现HTTP请求操 ...
2026-09-01 很多数据分析师面对业务问题时,常常感到“知道要分析,却不知道用什么方法”。其实,数据分析并非无章可循——从三大基础范 ...
2026-09-01在数据库设计与业务数据维护中,自增ID是数据表最常用的主键字段,用于唯一标识每一条业务数据,正常状态下ID应保持连续递增。但 ...
2026-08-31在数理统计、数据分析、经济测算与日常量化评估中,平均值是刻画数据集中趋势、反映整体水平的基础核心指标。在实际应用中,最常 ...
2026-08-31在数据驱动的时代,数据分析早已不是“凭经验、靠感觉”的零散操作,而是一套具备固定逻辑、标准化流程的系统方法——这就是数据 ...
2026-08-31在大数据时代背景下,海量行业数据亟需通过专业化工具挖掘潜在价值,辅助企业业务决策、优化运营模式、规避经营风险。Python凭借 ...
2026-08-28