python 文件与目录操作

yipeiwu_com6年前Python基础
1)os.path
1.1 os.path.isabs(path) 是否是绝对路径
1.2 os.path.isfile(path)
1.3 os.path.isdir(path)
1.4 os.path.islink(path) 是否是链接;但如果系统不支持链接,返回False
1.5 os.path.ismount(path) 是否为驱动器;但是很不幸的是在python 3.0中这是个不能运行的函数。
原函数如下:


# Is a path a mount point? Either a root (with or without drive letter)
# or an UNC path with at most a / or \ after the mount point.

def ismount(path):
"""Test whether a path is a mount point (defined as root of drive)"""
unc, rest = splitunc(path)
seps = _get_bothseps(p)
if unc:
return rest in p[:0] + seps
p = splitdrive(path)[1]
return len(p) == 1 and p[0] in seps




其错误之处是显而易见的。不知道这个函数为什么这么写,在windows平台,可以如下完成该功能
def ismount(path):
p = splitdrive(path)[1]
if len(p) > 0:
return(False)
else:
return(True)


其他平台没有对应的机器,不知道具体情形。
1.6 os.path.abspath(path) 返回绝对路径
1.7 os.path.dirname(path)
1.8 os.path.exists(path)
1.9 os.path.lexists(path) 和exists函数一样
1.10os.path.getsize(path)
1.11os.path.getctime(path) 返回浮点数的系统时间,在类Unix系统上是文件最近更改的时间,
在Windows上是文件或目录的创建时间
1.12os.path.getmtime(path) 文件或目录最后更改的时间
1.13os.path.getatime(path) 文件或目录最后存取的时间
1.14os.path.samefile(path1,path2) 如果2个路径指向同样的文件或目录,返回True(Windows上不可用)
1.15os.path.split(path) 分割路径,如果path是目录,返回[parentName, dirName];
如果path是文件,返回[dirName, fileName]
1.16os.path.splitext(path) 分割路径,如果path是目录,返回[parentName, ''];
如果path是文件,返回[dirName+fileName, 文件后缀]


2)fileinput
简单使用
import file
input for line in fileinput.input():
process(line)


2.1 fileinput.input([files[, inplace[, backup[,mode[,openhook]]]]])
创建一个fileinput的实例,如果files为空,则指向控制台获得输入;如果file为'-',同样转向控制台获得输入。
默认情况,文件以text mode打开,如果需要其他格式,则需要指定。
2.2 fileinput.filename() #只有当读入第一行之后,该值才被赋值
2.3 fileinput.fileno()
2.4 fileinput.lineno()
2.5 fileinput.filelineno()
2.6 fileinput.isfirstline()
2.7 fileinput.isstdin()
2.8 fileinput.nextfile()
2.9 fileinput.close()


3)glob
可以使用简单的方法匹配某个目录下的所有子目录或文件,用法也很简单。
3.1 glob.glob(regression) 返回一个列表
3.2 glob.iglob(regression) 返回一个遍历器
这个模块简单好用,强力推荐。


4)linecache
看名字就知道了,属于缓存类的
4.1 linecache.getline(filename,lineno[, module_globals]) #获得filename的第lineno行
4.2 linecache.clearcache()
4.3 linecache.checkcache([filename]) #检查更新


5)shutil 重点推荐的袄,好东西,支持文件集合的复制和删除操作
5.1 shutil.copyfileobj(fsrc, fdst[, length])
5.2 shutil.copyfile(src, dst) #上面2个都是文件的复制
5.3 shutil.copymode(src, dst) #除了复制内容,还会复制其他的一些信息,例如作者
5.4 shutil.copystat(src, dst) #除了复制内容,还会复制存取时间的信息
5.5 shutil.copy(src, dst) #复制文件到dst,当dst为目录时,复制到子目录
5.6 shutil.copy2(src, dst) #相当于先copy再copystat
5.7 shutil.copytree(src, dst[, symlinks=False[, ingore=None]]) #复制文件夹树,注意,dst文件夹必须是不存在的
5.8 shutil.rmtree(path[, ignore_erros[, onerror]])
5.9 shutil.move(src,dst)
复制代码 代码如下:

def copytree(src, dst, symlinks=False):
names = os.listdir(src)
os.makedirs(dst)
errors = []
for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks)
else:
copy2(srcname, dstname)
# XXX What about devices, sockets etc.?
except (IOError, os.error) as why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error as err:
errors.extend(err.args[0])
try:
copystat(src, dst)
except WindowsError:
# can't copy file access times on Windows
pass
except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
raise Error(errors)

相关文章

Python vtk读取并显示dicom文件示例

Python vtk读取并显示dicom文件示例

因为做项目的原因,所以接触到了医学图像dicom文件。vtk刚开始看,这里仅仅只是其最简单的读取显示功能。此处用到了vtk库,可自行百度安装方法。 下面附上代码: from vtk...

使用apidocJs快速生成在线文档的实例讲解

使用apidocJs快速生成在线文档的实例讲解

apidoc是一个轻量级的在线REST接口文档生成系统,支持多种主流语言,包括Java、C、C#、PHP和Javascript等。使用者仅需要按照要求书写相关注释,就可以生成可读性好、界...

基于Python代码编辑器的选用(详解)

基于Python代码编辑器的选用(详解)

Python开发环境配置好了,但发现自带的代码编辑器貌似用着有点不大习惯啊,所以咱们就找一个“好用的”代码编辑器吧,网上搜了一下资料,Python常用的编辑器有如下一些: 1. Subl...

python给指定csv表格中的联系人群发邮件(带附件的邮件)

以下为使用python给指定路径的csv表格中的联系人群发带附件的邮件(csv表格的第一列为联系人姓名,第二列为联系人邮箱账号)的代码,详情见注释。 import time impo...

在SQLite-Python中实现返回、查询中文字段的方法

博主在这个问题上卡了挺久的,贴出来解决方法帮助需要的朋友,直接上代码(测试环境:win10+Python2.7): # coding=utf-8 import sqlite3...