python(file)文件操作os
Python有关文件、文件夹操作小结:
import os,shutil #要用到这两个模块<strong><span style="color: #0000ff;">创建文件:</span></strong>1) os.mknod("test.txt") 创建空文件2) open("test.txt",w) 直接打开一个文件,如果文件不存在则创建文件<span style="color: #0000ff;"><strong>创建目录:</strong></span>os.mkdir("file") 创建目录<strong><span style="color: #0000ff;">复制文件:</span></strong>shutil.copyfile("oldfile","newfile") oldfile和newfile都只能是文件shutil.copy("oldfile","newfile") oldfile只能是文件夹,newfile可以是文件,也可以是目标目录<strong><span style="color: #0000ff;">复制文件夹:</span></strong>shutil.copytree("olddir","newdir") olddir和newdir都只能是目录,且newdir必须不存在<strong><span style="color: #0000ff;">重命名文件(目录)</span></strong>os.rename("oldname","newname") 文件或目录都是使用这条命令<strong><span style="color: #0000ff;">移动文件(目录)</span></strong>shutil.move("oldpos","newpos") <strong><span style="color: #0000ff;">删除文件</span></strong>os.remove("file")<strong><span style="color: #0000ff;">删除目录</span></strong>os.rmdir("dir") 只能删除空目录shutil.rmtree("dir") 空目录、有内容的目录都可以删<strong><span style="color: #0000ff;">转换目录</span></strong>os.chdir("path") 换路径<strong><span style="color: #0000ff;">判断目标</span></strong>os.path.exists("goal") 判断目标是否存在os.path.isdir("goal") 判断目标是否目录os.path.isfile("goal") 判断目标是否文件 <br><span style="color: #999999;">参考:http://www.cnblogs.com/phoebus0501/archive/2011/01/19/1939646.html</span> |
三、os.path
如下表:
| 函数 | 描述 |
|---|---|
| 分隔 | |
| basename(p) | 去掉目录路径, 返回文件名:os.path.basename('D:\\Project\\python25\\Lib\\a.txt') #a.txt
|
| dirname(p) | 去掉文件名, 返回目录路径:os.path.dirname(D:\\Project\\python25\\Lib\\a.txt) #D:\Project\python25\Lib |
| join() | 将分离的各部分组合成一个路径名:Django项目中常用,settings.py
DIRNAME = os.path.dirname(__file__)
TEMPLATE_DIRS = (
os.path.join(DIRNAME, "themes"),
)
|
| split() | 返回 (dirname(), basename()) 元组:>>>DIRNAME = 'D:\\Project\\python25\\Lib\\a.txt'
>>>os.path.split(DIRNAME)
('D:\\Project\\python25\\Lib', 'a.txt')
|
| splitdrive() | 返回 (drivename, pathname) 元组:os.path.splitdrive(DIRNAME)
#('D:', '\\Project\\python25\\Lib\\a.txt')
|
| splitext() | 返回 (filename, extension) 元组os.path.splitext(DIRNAME)
#('D:\\Project\\python25\\Lib\\a', '.txt')
|
| 信息 | |
| getatime(filename) | 返回最近访问时间:gTime = os.path.getatime(os.getcwd())
print gTime #1372836299.77
tTime = time.localtime(gTime)
print time.strftime('%Y-%m-%d %H:%M:%S',tTime) #2013-07-03 15:24:59
|
| getctime(filename) | 返回文件创建时间:cTime = os.path.getctime(os.getcwd())
c_time = time.localtime(cTime)
print time.strftime('%Y-%m-%d %H:%M:%S',c_time) #2013-04-17 17:27:46
|
| getmtime(filename) | 返回最近文件修改时间 |
| getsize(filename) | 返回文件大小(以字节为单位) |
| 查询 | |
| exists() | 指定路径(文件或目录)是否存在 |
| isabs() | 指定路径是否为绝对路径 |
| isdir() | 指定路径是否存在且为一个目录 |
| isfile() | 指定路径是否存在且为一个文件 |
| islink() | 指定路径是否存在且为一个符号链接 |
|
ismount() samefile() |
指定路径是否存在且为一个挂载点 两个路径名是否指向同个文件 |


浙公网安备 33010602011771号