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

python os模块常用操作文件目录方法

2017-11-20 00:00 876 查看
python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。
os.sep  #可以取代操作系统特定的路径分割符。
os.curdir('.')  #返回但前目录
os.path.normpath(path)  #规范path字符串形式
os.getcwd() #函数得到当前工作目录,即当前Python脚本工作的目录路径。
os.remove()     #函数用来删除一个文件
os.removedirs(r“c:\python”) #删除多个目录
os.listdir(dirname) #列出dirname下的目录和文件
os.path.existe()    #函数用来检验给出的路径是否真地存在
os.getcwd() #获得当前工作目录
os.path.isfile()    #检验给出的路径是否是一个文件
os.path.isdir() #检验给出的路径是否是一个目录
os.path.isabs() #判断是否是绝对路径
os.path.exists()    #检验给出的路径是否真地存
os.path.split(name):    #分割文件名与目录
# (事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,
# 同时它不会判断文件或目录是否存在)
os.path.splitext()  #分离扩展名
os.path.dirname()   #获取路径名
os.path.basename()  #获取文件名
os.system() #运行shell命令
os.getenv() 与os.putenv() #读取和设置环境变量
给出当前平台使用的行终止符:os.linesep Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
指示你正在使用的平台:os.name对于Windows,它是'nt',而对于Linux / Unix用户,它是'posix'
os.rename(old, new) #重命名
os.makedirs(r“c:\python\test”)  #创建多级目录
os.mkdir(“test”)    #创建单个目录
os.stat(file)   #获取文件属性
os.chmod(file)  #修改文件权限与时间戳
os.exit()   #终止当前进程
os.path.getsize(filename)   #获取文件大小:
os.path.join(dir, filename) #结合目录名与文件名
os.chdir(dirname)   #改变工作目录到dirname
os.mkdir("file")    #创建目录
shutil.copyfile("oldfile", "newfile")   #复制文件
#oldfile和newfile都只能是文件

shutil.copy("oldfile", "newfile")
#oldfile只能是文件夹,newfile可以是文件,也可以是目标目录

shutil.copytree("olddir", "newdir") #复制文件夹
#olddir和newdir都只能是目录,且newdir必须不存在

os.rename("oldname", "newname") #重命名文件(目录)文件或目录都是使用这条命令
shutil.move("oldpos", "newpos") #移动文件(目录)
os.rmdir("dir") ##只能删除空目录
shutil.rmtree("dir")    #空目录、有内容的目录都可以删
os.chdir("path")#换路径
os.stat(path / file)    #返回文件的对应属性值
# st_mode(protection bits), st_ino(inode number), st_dev(device),
#  st_nlink(number of hard links), st_uid(user id of owner),
# st_gid(group id of owner), st_size(size of file, in bytes),
# st_atime(time of most recent access),
# st_mtime(time of most recent content modification),
# st_ctime(platform dependent;time of most recent metadata change on Unix,
# or the time of creation on Windows)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python os