
Python核心模块详解解之os模块_python os模块详解
Python核心模块详解解之os模块
os模块提供了多数操作系统的功能接口函数.当os模块被导入后,它会自适应于不同的操作系统平台,如posix或NT系统平台,os模块会根据不同的平台进行相应的操作.本节内容将对os模块提供的函数进行详细的解读.
1.1 文件操作函数
1.1.1 open()函数提供创建、打开、修改文件的功能。
Example 1-1. Using the os Module to Rename and Remove Files
#Filename: os-example-1.py
import os
import string
def replace(file, search_for, replace_with):
# replace strings in a text file
back = os.path.splitext(file)[0] + “.bak”
temp = os.path.splitext(file)[0] + “.tmp”
try:
# remove old temp file, if any
os.remove(temp)
except os.error:
pass
fi = open(file)
fo = open(temp, “w”)
for s in fi.readlines():
fo.write(string.replace(s, search_for, replace_with))
fi.close()
fo.close()
try:
# remove old backup file, if any
os.remove(back)
except os.error:
pass
# rename original to backup…
os.rename(file, back)
# …and temporary to original
os.rename(temp, file)
# try it out!
file = “samples/sample.txt”
replace(file, “hello”, “tjena”)
replace(file, “tjena”, “hello”)
1.1.2 rename()和remove()函数,对文件进行重命名和删除操作.请参照例1-1
1.2 目录操作
1.2.1 listdir()函数,返回指定目录下所有文件名,并保存于一列表中.但当前目录标记(.)和父目录标记(..)不在其中.
Example 1-2. Using the os Module to List the Files in a Directory
File: os-example-2.py
import os
for file in os.listdir(“samples”):
print file
1.2.2 getcwd()和chdir()函数,功能是获取和改变当前工作目录.
Example 1-3. Using the os Module to Change the Working Directory
#Filename: os-example-3.py
import os
# where are we?
cwd = os.getcwd()
print “1”, cwd
# go down
os.chdir(“samples”)
print “2”, os.getcwd()
# go back up
os.chdir(os.pardir)
print “3”, os.getcwd()
1.2.3 mkdir(),rmdir(),makedirs()和removedirs()函数用于创建和删除目录操作.mkdir,rmdir和makedirs,removedir的不同在于前者只创建和删除一级目录,而后者则能创建和删除多级目录.要删除非空目录则要用到shutil模块中的rmtree()函数,在shutil模块详解中有介绍.
Example 1-4. Create and Remove Multiple Directory Levels
#Filename: os-example-4.py
import os
os.makedirs(“test/multiple/levels”)
fp = open(“test/multiple/levels/file”, “w”)
fp.write(“inspector praline”)
fp.close()
# remove the file
os.remove(“test/multiple/levels/file”)
# and all empty directories above it
os.removedirs(“test/multiple/levels”)
1.3 文件属性操作
1.3.1stat()函数返回一个文件的所有属性,所有的属性都包含在一个元组中.而fstat()函数则返回一个已经打开的文件的所有属性.
Example 1-32. Get Information About a File数据分析培训
File: os-example-1.py
import os
import time
file = “samples/sample.jpg”
def dump(st):
mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime = st
print “- size:”, size, “bytes”
print “- owner:”, uid, gid
print “- created:”, time.ctime(ctime)
print “- last accessed:”, time.ctime(atime)
print “- last modified:”, time.ctime(mtime)
print “- mode:”, oct(mode)
print “- inode/dev:”, ino, dev
# get stats for a filename
st = os.stat(file)
print “station”, file
dump(st)
print st
# get stats for an open file
fp = open(file)
st = os.fstat(fp.fileno())
print “fstat”, file
dump(st)
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
在数字化时代,用户的每一次行为 —— 从电商平台的 “浏览→加购→购买”,到视频 APP 的 “打开→搜索→观看→收藏”,再到银 ...
2025-10-11在机器学习建模流程中,“特征重要性分析” 是连接 “数据” 与 “业务” 的关键桥梁 —— 它不仅能帮我们筛选冗余特征、提升模 ...
2025-10-11在企业的数据体系中,未经分类的数据如同 “杂乱无章的仓库”—— 用户行为日志、订单记录、商品信息混杂存储,CDA(Certified D ...
2025-10-11在 SQL Server 数据库操作中,“数据类型转换” 是高频需求 —— 无论是将字符串格式的日期转为datetime用于筛选,还是将数值转 ...
2025-10-10在科研攻关、工业优化、产品开发中,正交试验(Orthogonal Experiment)因 “用少量试验覆盖多因素多水平组合” 的高效性,成为 ...
2025-10-10在企业数据量从 “GB 级” 迈向 “PB 级” 的过程中,“数据混乱” 的痛点逐渐从 “隐性问题” 变为 “显性瓶颈”:各部门数据口 ...
2025-10-10在深度学习中,“模型如何从错误中学习” 是最关键的问题 —— 而损失函数与反向传播正是回答这一问题的核心技术:损失函数负责 ...
2025-10-09本文将从 “检验本质” 切入,拆解两种方法的核心适用条件、场景边界与实战选择逻辑,结合医学、工业、教育领域的案例,让你明确 ...
2025-10-09在 CDA 数据分析师的日常工作中,常会遇到这样的困惑:某电商平台 11 月 GMV 同比增长 20%,但究竟是 “长期趋势自然增长”,还 ...
2025-10-09Pandas 选取特定值所在行:6 类核心方法与实战指南 在使用 pandas 处理结构化数据时,“选取特定值所在的行” 是最高频的操作之 ...
2025-09-30球面卷积神经网络(SCNN) 为解决这一痛点,球面卷积神经网络(Spherical Convolutional Neural Network, SCNN) 应运而生。它通 ...
2025-09-30在企业日常运营中,“未来会怎样” 是决策者最关心的问题 —— 电商平台想知道 “下月销量能否达标”,金融机构想预判 “下周股 ...
2025-09-30Excel 能做聚类分析吗?基础方法、进阶技巧与场景边界 在数据分析领域,聚类分析是 “无监督学习” 的核心技术 —— 无需预设分 ...
2025-09-29XGBoost 决策树:原理、优化与工业级实战指南 在机器学习领域,决策树因 “可解释性强、处理非线性关系能力突出” 成为基础模型 ...
2025-09-29在标签体系的落地链路中,“设计标签逻辑” 只是第一步,真正让标签从 “纸上定义” 变为 “业务可用资产” 的关键,在于标签加 ...
2025-09-29在使用 Excel 数据透视表进行多维度数据汇总时,折叠功能是梳理数据层级的核心工具 —— 通过点击 “+/-” 符号可展开明细数据或 ...
2025-09-28在使用 Pandas 处理 CSV、TSV 等文本文件时,“引号” 是最容易引发格式混乱的 “隐形杀手”—— 比如字段中包含逗号(如 “北京 ...
2025-09-28在 CDA(Certified Data Analyst)数据分析师的技能工具箱中,数据查询语言(尤其是 SQL)是最基础、也最核心的 “武器”。无论 ...
2025-09-28Cox 模型时间依赖性检验:原理、方法与实战应用 在生存分析领域,Cox 比例风险模型(Cox Proportional Hazards Model)是分析 “ ...
2025-09-26检测因子类型的影响程度大小:评估标准、实战案例与管控策略 在检测分析领域(如环境监测、食品质量检测、工业产品合规性测试) ...
2025-09-26