分享

python必掌握模块(六)os模块的使用

 liqualife 2019-09-21

一、为什么我们需要引用os模块

  • 在用python处理数据的过程中,经常需要查找操作文件和路径,这就依赖于os模块,我们今天只梳理最常用最简单的方法。

二、os模块使用方法

2.1、os.getcwd( )方法获取代码当前工作路径

import os
os.getcwd()
os.getcwd( )方法获取代码当前工作路径

2.2、 os.listdir()方法获取当前工作文件夹内的文件夹或文件

import os
os.listdir()
os.listdir()方法获取当前工作文件夹内的文件夹或文件

2.3 、 os.scandir() 方法获取当前工作文件夹内的文件夹或文件

os.scandir('/home/davidwu/kaggle')
os.scandir() 方法获取当前工作文件夹内的文件夹或文件

返回的是可迭代对象对吧?

我们用for循环迭代一下遍出结果

for f in os.scandir():
if not f.is_file(): #is_file判断是否是文件
print('yes',f)
else:
print('no:', f)
for循环迭代遍历出结果

2.4 、 os.makedirs() # 创建文件夹

os.makedirs('haha1/haha2') # 创建文件夹
os.makedirs() # 创建文件夹

2.5 、 os.chdir( ) # 创建文件夹

os.chdir('/home/davidwu/kaggle/haha1/haha2')
os.chdir( ) # 创建文件夹

2.6 、 os.path.join() # 路径拼接为

os.path.join('kaggle', 'kaggle233', 'kaggle666')

2.7 、 os.path.abspath( ) # os.path.abspath(path):返回path的绝对路径。

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

2.8 、 os.system(command) #用来运行shell命令。

python调用Shell脚本,有两种方法:os.system(cmd)或os.popen(cmd),前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多