python中对文件、文件夹的操作需要涉及到os模块和shutil模块。
- 创建文件:
os.mknod("test.txt") #创建空文件 windows 函数
fd = open("test.txt",w) #直接打开一个文件,如果文件不存在则创建文件
fd.write('abc\n')
fd.writelines(['line1', 'line2', 'line3'])
fd.close()
- 创建目录
os.mkdir(path) #创建目录,上级目录必须存在
os.makedirs(path) #创建多层目录
- 复制文件
#dst都必须是文件,不能是目录
shutil.copyfile(src,dst)
#如果dst是目录,会将src拷贝到dst目录下
#如果dst不是目录,会将拷贝生成一个dst文件,即生成的文件名变了
shutil.copy(src, dst) #拷贝生成一个新文件
- 复制文件夹
#将src目录下的文件和文件夹,拷贝到dst目录下,dst目录不可以存在,函数会自动创建
shutil.copytree(src,dst)
- 重命名文件(目录)
os.rename("oldname","newname") #文件或目录都是使用这条命令
- 移动文件(目录)
shutil.move("oldpos","newpos")
- 删除文件
os.remove("file")
- 删除目录
os.rmdir("dir") #只能删除空目录
shutil.rmtree("dir") #空目录、有内容的目录都可以删
- 转换目录
os.chdir("path") #换路径
- 判断目标
os.path.exists("goal") #判断目标是否存在
os.path.isdir("goal") #判断目标是否目录
os.path.isfile("goal") #判断目标是否文件
备注:若路径中含中文,在windows环境(编码为GBK)下,要将目录编码成GBK,如:dir.encode('GBK')
示例1:
创建目录和文件,按行写入内容,拷贝文件和文件夹
import os, shutil
fd = open('test1.txt', 'w')
fd.write('line0\nline1\n')
fd.writelines(['lines2\n', 'lines3\n'])
fd.close()
os.mkdir('src')
os.mkdir('empty')
os.makedirs('src/sub0/sub1')
open('src/test2.txt', 'w').close()
open('src/test3.txt', 'w').close()
shutil.copy('test1.txt', 'test1_copy.txt')
shutil.copytree('src', 'dst')
raw_input('rename')
os.rename('test1.txt', 'test1_rename.txt')
shutil.move('test1_copy.txt', 'test1_move.txt')
os.rename('src', 'src_rename')
shutil.move('dst', 'dst_move')
raw_input('delete')
os.remove('test1_move.txt')
os.remove('test1_rename.txt')
os.rmdir('empty')
shutil.rmtree('src_rename')
shutil.rmtree('dst_move')
print 'done.'
- 创建多层目录
def mkdirs(path):
# 去除首位空格
path=path.strip()
# 去除尾部\符号
path=path.rstrip("\\")
# 判断路径是否存在
isExists=os.path.exists(path)
# 判断结果
if not isExists:
# 创建目录操作函数
os.makedirs(path)
# 如果不存在则创建目录
print path + u' 创建成功'
return True
else:
# 如果目录存在则不创建,并提示目录已存在
print path + u' 目录已存在'
return False