3Python标准库系列之os模块

简介:

Python标准库系列之os模块


This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module


os模块常用方法


模块方法 说明
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir(“dirname”) 改变当前脚本工作目录;相当于shell下cd
os.curdir 返回当前目录: (‘.’)
os.pardir 获取当前目录的父目录字符串名:(‘..’)
os.makedirs(‘dirname1/dirname2’) 可生成多层递归目录
os.removedirs(‘dirname1’) 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir(‘dirname’) 生成单级目录;相当于shell中mkdir dirname
os.rmdir(‘dirname’) 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir(‘dirname’) 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename(“oldname”,”newname”) 重命名文件/目录
os.stat(‘path/filename’) 获取文件/目录信息
os.sep 输出操作系统特定的路径分隔符,win下为\\,Linux下为/
os.linesep 输出当前平台使用的行终止符,win下为\t\n,Linux下为\n
os.pathsep 输出用于分割文件路径的字符串
os.name 输出字符串指示当前使用平台。win->nt; Linux->posix
os.system(“bash command”) 运行shell命令,直接显示
os.environ 获取系统环境变量
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) 如果path是绝对路径,返回True
os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[,…]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间


常用方法实例

获取当前工作目录

1
2
3
  # 获取的进入python时的目录
  >>> os.getcwd()
'/root'


改变工作目录到/tmp

1
2
3
4
5
6
7
8
  # 当前目录是/root
  >>> os.getcwd()
'/root'
  # 切换到/tmp下
  >>> os.chdir( "/tmp" )
  # 当前目录变成了/tmp
  >>> os.getcwd()     
'/tmp'


获取/root目录下的所有文件,包括隐藏文件

1
2
  >>> os.listdir( '/root' )
[ '.cshrc' '.bash_history' '.bash_logout' '.viminfo' '.bash_profile' '.tcshrc' 'scripts.py' '.bashrc' 'modules' ]


删除/tmp目录下的os.txt文件

1
2
3
4
5
6
7
8
  >>> os.chdir( "/tmp"
  >>> os.getcwd()     
'/tmp'
  >>> os.listdir( './' )   
[ '.ICE-unix' 'yum.log' ]
  >>> os.remove( "yum.log" )
  >>> os.listdir( './' )    
[ '.ICE-unix' ]


查看/root目录信息

1
2
  >>> os.stat( '/root' )        
posix.stat_result(st_mode = 16744 , st_ino = 130817 , st_dev = 2051L , st_nlink = 3 , st_uid = 0 , st_gid = 0 , st_size = 4096 , st_atime = 1463668203 , st_mtime = 1463668161 , st_ctime = 1463668161 )


查看当前操作系统的平台

1
2
  >>> os.name
'posix'

win —> nt,Linux -> posix


执行一段shell命令

1
2
3
4
5
   # 执行的命令要写绝对路径
  >>> os.system( "/usr/bin/whoami" )    
root
# 0代表命令执行成功,如果命令没有执行成功则返回的是非0
0


组合一个路径

1
2
3
4
  >>> a1  =  "/"
  >>> a2  =  "root"
  >>> os.path.join(a1, a2)
'/root'









本文转自 Edenwy  51CTO博客,原文链接:http://blog.51cto.com/edeny/1925712,如需转载请自行联系原作者
目录
相关文章
Python
13 0
|
1天前
|
JSON 数据格式 索引
python 又一个点运算符操作的字典库:Munch
python 又一个点运算符操作的字典库:Munch
10 0
|
1天前
|
开发者 Python
Python的os模块详解
Python的os模块详解
11 0
|
1天前
|
数据挖掘 数据处理 索引
如何使用Python的Pandas库进行数据筛选和过滤?
Pandas是Python数据分析的核心库,提供DataFrame数据结构。基本步骤包括导入库、创建DataFrame及进行数据筛选。示例代码展示了如何通过布尔索引、`query()`和`loc[]`方法筛选`Age`大于19的记录。
10 0
|
2天前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名
【4月更文挑战第22天】Pandas Python库提供数据排序和排名功能。使用`sort_values()`按列进行升序或降序排序,如`df.sort_values(by='A', ascending=False)`。`rank()`函数用于计算排名,如`df['A'].rank(ascending=False)`。多列操作可传入列名列表,如`df.sort_values(by=['A', 'B'], ascending=[True, False])`和分别对'A'、'B'列排名。
13 2
|
3天前
|
算法 Python
请解释Python中的关联规则挖掘以及如何使用Sklearn库实现它。
使用Python的mlxtend库,可以通过Apriori算法进行关联规则挖掘。首先导入TransactionEncoder和apriori等模块,然后准备数据集(如购买行为列表)。对数据集编码并转换后,应用Apriori算法找到频繁项集(设置最小支持度)。最后,生成关联规则并计算置信度(设定最小置信度阈值)。通过调整这些参数可以优化结果。
25 9
|
3天前
|
Python
如何使用Python的Pandas库进行数据缺失值处理?
Pandas在Python中提供多种处理缺失值的方法:1) 使用`isnull()`检查;2) `dropna()`删除含缺失值的行或列;3) `fillna()`用常数、前后值填充;4) `interpolate()`进行插值填充。根据需求选择合适的方法处理数据缺失。
35 9
|
3天前
|
索引 Python
如何在Python中使用Pandas库进行季节性调整?
在Python中使用Pandas和Statsmodels进行季节性调整的步骤包括:导入pandas和seasonal_decompose模块,准备时间序列DataFrame,调用`seasonal_decompose()`函数分解数据为趋势、季节性和残差,可选地绘制图表分析,以及根据需求去除季节性影响(如将原始数据减去季节性成分)。这是对时间序列数据进行季节性分析的基础流程。
19 2
|
4天前
|
数据挖掘 API 数据安全/隐私保护
python请求模块requests如何添加代理ip
python请求模块requests如何添加代理ip
|
5天前
|
缓存 自然语言处理 数据处理
Python自然语言处理面试:NLTK、SpaCy与Hugging Face库详解
【4月更文挑战第16天】本文介绍了Python NLP面试中NLTK、SpaCy和Hugging Face库的常见问题和易错点。通过示例代码展示了如何进行分词、词性标注、命名实体识别、相似度计算、依存关系分析、文本分类及预训练模型调用等任务。重点强调了理解库功能、预处理、模型选择、性能优化和模型解释性的重要性,帮助面试者提升NLP技术展示。
22 5

热门文章

最新文章