在python中对文件目录的操作经常用到os模块和shutil模块,接下来整理一些操作文件和目录的常用方法:
- 获取当前Python脚本工作的目录路径:os.getcwd()
- 返回指定目录下的所有文件和目录名:os.listdir() 例如:返回c盘下的文件:os.listdir('c:\\')
- 删除一个文件:os.remove(filepath)
- 删除多个空目录:os.removedirs(r'd:\python')
- 检验给出的路径是否是一个文件:os.path.isfile(filepath)
- 检验给出的路径是否是一个目录:os.path.isdir(filepath)
- 判断是否绝对路径:os.path.isabs()
- 检验路径是否真的存在:os.path.exists() 例如:检查d盘下是否有python文件:os.path.exists('d:/python')
- 分离一个路径的目录名和文件名:os.path.split() 例如:os.path.split('/home/qiye/qiye.txt') 返回是一个元组(‘/home/qiye’,'qiye.txt')
- 分离扩展名:os.path.splitext() 例如os.path.splitext('/home/qiye/qiye.txt') 返回结果是一个元组:('/home/qiye/qiye','.txt')
- 获取路径名:os.path.dirname(filepath)
- 获取文件名:os.path.basename(filepath)
- 读取和设置环境变量:os.getenv() 与os.putenv()
- 给出当前平台使用的行终止符:os.linesep Windows使用'\r\n',对于linux用户,是:‘posix'
- 重命名文件或者目录:os.rename(old,new)
- 创建多级目录:os.makedirs('c:/python/test')
- 创建单个目录:os.mkdir('test')
- 获取文件属性:os.stat(file)
- 修改文件权限与时间戳:os.chmod(file)
- 获取文件大小:os.path.getsize(filepath)
- 复制文件夹:shutil.copytree('olddir','newdir') olddir和newdir只能是目录,且newdir必须不存在
- 复制文件:shulit.copyfile('oldfile','newfile') oldfile和newfile只能是文件, shulit.copy(oldfile,newfile) oldfile只能是文件,newfile可以是文件也可以是目录
- 移动文件(目录):shulit.move(‘oldpos’,‘newpos’)
- 删除目录:os.rmdir(‘dir’) 只能删除空目录;shutil.rmtree(‘dir’),空目录,有内容的目录都可以删