# -*- coding: utf-8 -*- import os print os.name #windows为nt,linux为posix path = os.getcwd() #获得当前脚本所在目录 print path total_name = os.path.join(path, '123.txt') folder,name = os.path.split(total_name) #将路径分解为路径名和文件名 print folder.decode('gbk'), name.decode('gbk') print os.path.dirname(total_name) #路径名 print os.path.basename(total_name) #文件名 file_name, ext_name = os.path.splitext(name) #将文件名和扩展名 print file_name.decode('gbk'), ext_name if not os.path.exists('temp'): #判断一个路径或目录或文件是否存在 print u'不存在' os.mkdir('temp') #创建文件夹 os.makedirs('temp\subtemp') #创建多级目录 print os.path.isfile(u'os模块.py') #判断一个文件是否存在 print os.path.isdir('temp') #判断一个路径是否存在 print os.listdir('c:\') #获取目录中的文件及子目录列表,包括隐藏的 os.system('dir') #运行shell命令 print os.path.abspath('.').decode('gbk') #获取绝对路径 f = open('123.txt','w') f.write('hello') f.close() print os.path.getsize('123.txt') #获取文件大小,若为目录则返回0 os.rename('123.txt', '456.txt') os.remove('456.txt') #删除文件 os.chdir('temp') #改变当前目录 os.rmdir('subtemp') #删除子目录,只能删除空目录
删除整个目录,不用担心是否为空,用:
import shutil
shutil.rmtree()