python-os模块学习

来源:互联网 发布:python xpath爬虫text 编辑:程序博客网 时间:2024/06/05 18:31

OS模块提供了与操作系统打交道时常用的功能实现,换句话说,要是你想让你的代码跑在不同的操作平台上,这个模块是不可以不掌握的。

一.常用方法

1.os.getcwd()

返回当前的工作目录

>>> import os>>> print os.getcwd()C:\Users\Tamarous\Documents\Visual Studio 2012\Projects\work1\work1</span>

2.os.listdir()

返回指定的路径下的所有文件和目录

>>> print os.listdir(r'C:/')['$Recycle.Bin', 'alipay', 'Biography', 'Boot', 'bootmgr', 'BOOTNXT', 'Config.Msi', 'dbchd', 'dbchd.mbr', 'Dell', 'Documents and Settings', 'Flashtool', 'found.000', 'iBTWU', 'IDBC', 'Intel', 'MSOCache', 'pagefile.sys', 'PerfLogs', 'Program Files', 'Program Files (x86)', 'ProgramData', 'Progra~1', 'Python27', 'swapfile.sys', 'System Volume Information', 'Users', 'Windows']

3.os.remove()

删除一个文件

4.os.walk()

遍历指定的路径,返回一个三元组dirpath, dirnames, filenames

#-*- coding:utf-8 -*-import osimport os.pathpath = r'C:\Python27'for root,dirs,files in os.walk(path):    for file in files:        print  os.path.join(file)
5.os.path.split()

返回一个路径的目录名和文件名

>>> print os.path.split(r'C:\Python27\Doc\python276.chm')('C:\\Python27\\Doc', 'python276.chm')

6.os.path.exists()

检测一个路径是否真的存在,存在返回True,不存在返回False

>>> print os.path.exists('C:\\Python27\\Doc\\')True>>> print os.path.exists('C:\\Python27\\Love\\')False


7.os.path.getsize()

返回文件的大小,以字节表示

>>> print os.path.getsize(r'C:\Python27\Doc\python276.chm')6010777

8.os.path.splitext()

分离文件名与扩展名

>>> print os.path.splitext('python276.chm')('python276', '.chm')


9.os.path.basename(path)

返回文件名

>>> print os.path.basename(r'C:\Python27\Doc\python276.chm')python276.chm


10.os.path.dirname(path)

返回文件路径

>>> print os.path.dirname(r'C:\Python27\Doc\python276.chm')C:\Python27\Doc













0 0
原创粉丝点击