python中对文件、文件夹的操作需要涉及到os模块和shutil模块。
- 创建空文件 - 1 - os.mknod("test.txt") 
- 直接打开一个文件,如果文件不存在则创建文件 - 1 - open("test.txt",w) 
- 创建目录 - 1 - os.mkdir("file") 
- 创建多层新目录: - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22- def mkdirs(path): 
 # 去除首位空格
 path=path.strip()
 # 去除尾部 \ 符号
 path=path.rstrip(“\“)
 
 # 判断路径是否存在
 # 存在 True
 # 不存在 False
 isExists = os.path.exists(path)
 
 # 判断结果
 if not isExists:
 # 创建目录操作函数
 os.makedirs(path)
 # 如果不存在则创建目录
 print path + u’ 创建成功’
 return True
 else:
 # 如果目录存在则不创建,并提示目录已存在
 print path + u’ 目录已存在’
 return False
- 复制文件 - 1 
 2- shutil.copyfile(“oldfile”,“newfile”) #oldfile和newfile都只能是文件 
 shutil.copy(“oldfile”,“newfile”) #oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
- 复制文件夹 - 1 - hutil.copytree(“olddir”,“newdir”) #olddir和newdir都只能是目录,且newdir必须不存在 
- 重命名文件(目录) - 1 - os.rename(“oldname”,“newname”) #文件或目录都是使用这条命令 
- 移动文件(目录) - 1 - shutil.move(“oldpos”,“newpos”) 
- 删除文件 - 1 - os.remove(“file”) 
- 删除目录 - 1 
 2- os.rmdir(“dir”) #只能删除空目录 
 shutil.rmtree(“dir”) #空目录、有内容的目录都可以删
- 转换目录 - 1 - os.chdir(“path”) #却换到指定路径下 
- 判断目标 - 1 
 2
 3- os.path.exists(“goal”) #判断目标是否存在 
 os.path.isdir(“goal”) #判断目标是否目录
 os.path.isfile(“goal”) #判断目标是否文件
备注: 若路径中含中文,在windows环境(编码为GBK)下,要将目录编码成GBK,如:dir.encode(‘GBK’)
转载自:http://l90z11.blog.163.com/blog/static/187389042201312153318389/
