Python操作文件和目录
1、获得当前Python脚本工作的目录:os.getcwd()
2、返回指定目录下所有文件和目录名:os.listdir(path),如:os.listdir("C:\\")
3、删除一个文件:os.remove(filepath)
4、删除多个空目录:s.removedirs(r"C:\pathname")
5、检验给出的路径是不是一个文件:os.path.isfile(filepath)
6、检验给出的路径是不是一个目录:os.path.isdir(filepath)
7、判断是否为绝对路径:os.path.isabs()
8、检验给的路径是否存在:os.path.exists(path)
9、分离一个路径的目录名和文件名,返回元组(filepath,filename):os.path.split(path)
10、获取路径名:os.path.dirname(filepath)
11、分离扩展名:os.path.splitext(),如os.path.splitext('D:\static\iconfont.css'),返回值为:('D:\\static\\iconfont', '.css')
12、读取和设置环境变量:os.getenv(),os.putenv()。如os.getenv('TMP'),
13、获取正在使用的平台:os.name。对于Windows,返回'nt',Linux/Unix返回'posix'
14、重命名文件或目录:os.rename(old,new)
15、创建多级目录:os.makedirs("D:\Python\project")
16、创建单个目录:os.mkdir('test')
17、获取文件属性:os.stat(file)
18、修改文件权限和时间戳:os.chmod(file)
19、获取文件大小:os.path.getsize(filename)
20、复制文件夹:shutil.copytree(oldpath,newpath),两个参数都只能是目录,且newpath必须不存在
21、复制文件:shutil.copyfile(oldfile,newfile),两个参数都只能是文件,shutil.copy(oldfile,newfile),oldfile只能是文件,newfile可以是文件也可以是目录
22、移动文件(目录):shutil.move(oldposition,newposition)
23、删除目录:os.rmdir(dir),只能删除空目录。shutil.rmtree(dir),空目录,有内容的目录都可能删除。

浙公网安备 33010602011771号