Python--os模块--shutil

来源:互联网 发布:阿里云 网站备案 编辑:程序博客网 时间:2024/06/05 09:40

os 文件/目录方法

import os# 得到当前的工作目录path=os.getcwd()# 返回制定目录下所有文件和目录名# 返回listdir = os.listdir(path)print dir,type(dir)# ['error.log', 'File_op.py', 'file_os.py', '__init__.py'] <type 'list'># 修改当前工作目录os.chdir("/tmp")# 检测路径是不是文件os.path.isfile()# 检测路径是不是目录os.path.isdir()# 检测是否是绝对路径os.path.isabs()# 检测路径是否存在os.path.exists()#重命名os.rename(old,new)# 获取文件大小os.path.getsize(filename)# 创建目录os.mkdir("test")# 创建多级目录os.makedirs("d:\\xx\\x")# 删除文件os.remove()# 删除多个文件os.removedirs()# 分割一个路径下的路径和文件名os.path.split()# os.path.split('/home/swaroop/byte/code/poem.txt')# 结果:('/home/swaroop/byte/code', 'poem.txt')# 分离扩展名print os.path.splitext('/home/swaroop/byte/code/poem.txt')# ('/home/swaroop/byte/code/poem', '.txt')# 获取路径print os.path.dirname('/home/swaroop/byte/code/poem.txt')# 获取文件名print os.path.basename('/home/swaroop/byte/code/poem.txt')# poem.txt# 运行shell命令os.system("ls")# 读取和设置环境变量os.getenv()os.putenv()#终止当前进程os.exit()#指示你正在使用的平台:os.name    #对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix' print "os.name: ",os.name #给出当前平台使用的行终止符:os.linesep  #Windows使用'\r\n',Linux使用'\n'而Mac使用'\r' print(os.linesep) 
import shutil#oldfile和newfile都只能是文件shutil.copyfile("oldfile","newfile")#oldfile只能是文件夹,newfile可以是文件,也可以是目标目录       shutil.copy("oldfile","newfile")  #移动文件(目录)shutil.move("oldpos","newpos")            
原创粉丝点击