【转载】文件操作的其他方式
摘自:http://l90z11.blog.163.com/blog/static/187389042201312153318389/
有删改,注意原文中有部分错误。比如os模块压根就没有mknod和rmdir属性,
shutil.copy()也只能是从文件复制到文件或文件夹
创建文件:open("test.txt",w) 直接打开一个文件,如果文件不存在则创建文件
创建目录:
os.mkdir("file")
print os.path.exists(path)
存在是True,不存在是False
复制文件:
shutil.copyfile("oldfile","newfile") oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile") oldfile只能是文件,newfile可以是文件,也可以是目标目录
也就是
import shutil
shutil.copyfile()
等于
file = open('path')
content = file.read()
other_file = open('other_path', 'w')
other_file.write(content)
复制文件夹:shutil.copytree("olddir","newdir") olddir和newdir都只能是目录,且newdir必须不存在
重命名文件或目录:os.rename("oldname","newname")
移动文件(目录):shutil.move("oldpos","newpos")
删除文件: os.remove("file")
删除目录: shutil.rmtree("dir") 空目录、有内容的目录都可以删
改变当前工作目录:
import os
print os.getcwd()
os.chdir('c: \\python')
print os.getcwd()
判断目标
os.path.exists("goal") 判断目标是否存在
os.path.isdir("goal") 判断目标是否目录
os.path.isfile("goal") 判断目标是否文件