您的位置:首页 > 编程语言 > Python开发

python中的os模块使用方法

2016-12-18 13:30 471 查看
#-*-coding:utf-8
'''
os.getcwd():得到当前的目录
os.listdir('g:\\python2') 获得g盘python2目录下的所有内容
os.system():运行shell命令,os.system('cmd'):起动dos
os.remove('g:\\file\\file.txt'):删除一个文件,不能删除一个目录
os.sep 可以取代操作系统特定的路径分割符。
os.mkdir(os.path.normpath('g:\\file'):创建一个目录

#os.path模块
os.path.split('g:\\file\\file.txt'):返回一个路径的目录名和文件名(以元组的形式,因此可以遍历)
os.path.splitext('file.py'):分离文件名和扩展名,返回的是('file','.py')以元组的方式返回
os.path.exists(''):用来检验给出的路径是否真实存在,若存在返回true
os.path.getsize('g:\\file\\file.txt'):获得文件的大小,如果是目录则返回0

os.path.normpath(name):规范路径的字符串形式,用与存储文件
os.path.basename(name):返回的是文件名,如os.path.basename('g:\\file\\file.py'):return file.py
os.path.dirname(path):返回的是文件的路径 :如os.path.dirname('g:\\file\\file.txt')  return g:\\file
'''
import os

#os.system('cmd')
print os.getcwd()  #获得当前的路径
print os.name       #获得当前操作系统
print os.listdir('g:\\python2')
print os.listdir('g://python2_workspace')
os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。

print os.system('dir')
os.remove('g:\\file\\file.txt')
print os.sep

p=os.path.split('g:\\file\\file.txt')
for i in p:
print i

print os.path.isfile(os.getcwd())
print os.path.isdir(os.getcwd())
print os.path.isfile('file.py')
print os.path.exists('g:\\python2\\file')

print os.path.abspath('file.txt')
print os.path.normpath('g:\\file')
print os.path.getsize('g:\\file')
print os.path.splitext('a.py')
print os.path.normpath('g:/file.jpg')
path=os.path.join('g:/file','file.txt')
print os.path.normpath(path)
print os.path.basename('g:\\file\\file.txt')
filename='g:\\file\\file'
path=os.path.normpath(filename)
print path
os.mkdir(path)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python