python中对文件、文件夹的操做须要涉及到os模块和shutil模块。python
import os os.mknod("test.txt") #建立空文件(在Mac os下使用会报权限不足错误) open("test.txt",w) #直接打开一个文件,若是文件不存在则建立文件
import os os.mkdir("file") #建立目录(文件夹)
建立多层新目录spa
import os os.makedirs("a/b/c") # 将会建立多层新目录 ``` . ├── a │ └── b │ └── c ```
判断路径code
import os is_exists = os.path.exists(path) #返回bool值True or False is_dir = os.path.isdir("goal") #判断目标是否目录bool is_file = os.path.isfile("goal") #判断目标是否文件bool
import shutil shutil.copyfile("oldfile","newfile") #oldfile和newfile都只能是文件 shutil.copy("oldfile","newfile") #复制文件的内容以及权限,先copyfile后copymode shutil.copymode(src,dst) #复制文件权限, 仅copy权限,不更改文件内容,组和用户。 ''' #运行命令 >>> import shutil >>> shutil.copymode('test1','test2') #查看结果 [root@slyoyo python_test]# ls -l total 4 -rw-r--r--. 1 root root 79 May 14 05:17 test1 -rw-r--r--. 1 root root 0 May 14 19:10 test2 ''' shutil.copytree("olddir","newdir") #olddir和newdir都只能是目录,且newdir必须不存在
import os os.rename("oldname","newname") #文件或目录都是使用这条命令
import shutil shutil.move("oldpos","newpos")
import os import shut os.remove("file") #删除文件 os.rmdir("dir") #只能删除空目录 shutil.rmtree("dir") #空目录、有内容的目录均可以删
os.chdir("path") #转换当前解释器环境所在目录