Python的os.path模块
- os.path.abspath(path) #返回绝对路径
- os.path.basename(path) #返回文件名
- os.path.commonprefix(list) #返回list(多个路径)中,所有path共有的最长的路径。
- os.path.dirname(path) #返回文件路径
- os.path.exists(path) #路径存在则返回True,路径损坏返回False
- os.path.lexists #路径存在则返回True,路径损坏也返回True
- os.path.expanduser(path) #把path中包含的”~”和”~user”转换成用户目录
- os.path.expandvars(path) #根据环境变量的值替换path中包含的”$name”和”${name}”
- os.path.getatime(path) #返回最后一次进入此path的时间。
- os.path.getmtime(path) #返回在此path下最后一次修改的时间。
- os.path.getctime(path) #返回path的大小
- os.path.getsize(path) #返回文件大小,如果文件不存在就返回错误
- os.path.isabs(path) #判断是否为绝对路径
- os.path.isfile(path) #判断路径是否为文件
- os.path.isdir(path) #判断路径是否为目录
- os.path.islink(path) #判断路径是否为链接
- os.path.ismount(path) #判断路径是否为挂载点()
- os.path.join(path1[, path2[, …]]) #把目录和文件名合成一个路径
- os.path.normcase(path) #转换path的大小写和斜杠
- os.path.normpath(path) #规范path字符串形式
- os.path.realpath(path) #返回path的真实路径
- os.path.relpath(path[, start]) #从start开始计算相对路径
- os.path.samefile(path1, path2) #判断目录或文件是否相同
- os.path.sameopenfile(fp1, fp2) #判断fp1和fp2是否指向同一文件
- os.path.samestat(stat1, stat2) #判断stat tuple stat1和stat2是否指向同一个文件
- os.path.split(path) #把路径分割成dirname和basename,返回一个元组
- os.path.splitdrive(path) #一般用在windows下,返回驱动器名和路径组成的元组
- os.path.splitext(path) #分割路径,返回路径名和文件扩展名的元组
- os.path.splitunc(path) #把路径分割为加载点与文件
- os.path.walk(path, visit, arg) #遍历path,进入每个目录都调用visit函数,visit函数必须有3个参数(arg,dirname,names),dirname表示当前目录的目录名,names代表当前目录下的所有文件名,args则为walk的第三个参数
- os.path.supports_unicode_filenames #设置是否支持unicode路径名
''' C:Python27>python Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os.path >>> dir(os.path) ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_abspath_split', '_getfullpathname', 'abspath', 'altsep', 'basename', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'genericpath', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'relpath', 'sep', 'split', 'splitdrive', 'splitext', 'splitunc', 'stat', 'supports_unicode_filenames', 'sys', 'walk', 'warnings'] >>> >>> help(os.path) Help on module ntpath: NAME ntpath - Common pathname manipulations, WindowsNT/95 version. FILE c:python27libntpath.py DESCRIPTION Instead of importing this module directly, import os and refer to this module as os.path. FUNCTIONS abspath(path) Return the absolute version of a path. basename(p) Returns the final component of a pathname commonprefix(m) Given a list of pathnames, returns the longest common leading component dirname(p) Returns the directory component of a pathname exists(path) Test whether a path exists. Returns False for broken symbolic links expanduser(path) Expand ~ and ~user constructs. If user or $HOME is unknown, do nothing. expandvars(path) Expand shell variables of the forms $var, ${var} and %var%. Unknown variables are left unchanged. getatime(filename) Return the last access time of a file, reported by os.stat(). getctime(filename) Return the metadata change time of a file, reported by os.stat(). getmtime(filename) Return the last modification time of a file, reported by os.stat(). getsize(filename) Return the size of a file, reported by os.stat(). isabs(s) Test whether a path is absolute isdir = _isdir(...) Return true if the pathname refers to an existing directory. isfile(path) Test whether a path is a regular file islink(path) Test for symbolic link. On WindowsNT/95 and OS/2 always returns false ismount(path) Test whether a path is a mount point (defined as root of drive) join(a, *p) Join two or more pathname components, inserting "" as needed. If any component is an absolute path, all previous path components will be discarded. lexists = exists(path) Test whether a path exists. Returns False for broken symbolic links normcase(s) Normalize case of pathname. Makes all characters lowercase and all slashes into backslashes. normpath(path) Normalize path, eliminating double slashes, etc. realpath = abspath(path) Return the absolute version of a path. relpath(path, start='.') Return a relative version of a path split(p) Split a pathname. Return tuple (head, tail) where tail is everything after the final slash. Either part may be empty. splitdrive(p) Split a pathname into drive and path specifiers. Returns a 2-tuple "(drive,path)"; either part may be empty splitext(p) Split the extension from a pathname. Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty. splitunc(p) Split a pathname into UNC mount point and relative path specifiers. Return a 2-tuple (unc, rest); either part may be empty. If unc is not empty, it has the form '//host/mount' (or similar using backslashes). unc+rest is always the input path. Paths containing drive letters never have an UNC part. walk(top, func, arg) Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common. DATA __all__ = ['normcase', 'isabs', 'join', 'splitdrive', 'split', 'splite... altsep = '/' curdir = '.' defpath = r'.;C:bin' devnull = 'nul' extsep = '.' pardir = '..' pathsep = ';' sep = r'' supports_unicode_filenames = True >>> '''
批量重命名:
import os, time, glob for files in glob.glob('D:\photos\*.jpg'): filepath,filename = os.path.split(files) filterame,exts = os.path.splitext(filename) opfile = 'D:\photos2\' # output path if (os.path.isdir(opfile)==False): os.mkdir(opfile) path = os.path.normcase("D:/photos2/") cc = time.gmtime() bmpname = str(cc[0])+str(cc[1])+str(cc[2])+str(cc[3]+8)+str(cc[4])+str(cc[5])+'.bmp' os.remove(bmpname) # remove .bmp file jpgname = bmpname[:-4]+'.jpg' djpgname = path+jpgname copy_command = "move %s %s" % (jpgname, djpgname) os.popen(copy_command)
os.walk函数的一段代码示例(统计指定文件夹中的文件大小):
import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print root, "consumes", print sum([getsize(join(root, name)) for name in files]), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories
《“Python的os.path模块”》 有 1 条评论
用reload()重新加载python模块
https://paper.tuisec.win/detail/63e81b6144be91f
http://www.maixj.net/ict/reload-python-13587
`
一个python模块就是一个.py文件。
在python解释器中,我们import一个自己的模块之后,如果在模块代码修改后,需要重新加载,这对于调试很方便。那么,如何在python的解释器中重新加载模块呢?方法如下,就是使用一个reload函数。
方法一:基本方法
from imp import reload
reload(module)
方法二:按照套路,可以这样
import imp
imp.reload(module)
方法三:看看imp.py,有发现,所以还可以这样
import importlib
importlib.reload(module)
方法四:根据天理,当然也可以这样(Python3.4之后的推荐用法)
from importlib import reload
reload(module)
重新加载在调试的时候很方便,但是有一个小细节:重新加载不会删除原来已经存在的符号表已经其中的内容。
比如原来有个函数叫zaHello(),修改名称为Hello(),然后reload模块,这次用dir()还可以看到原来zaHello()存在,而且还能执行。
Python将importlib作为标准库提供。它旨在提供Python import语法和(__import__()函数)的实现。另外,importlib提供了开发者可以创建自己的对象(即importer)来处理导入过程。
那么imp呢?还有一个imp模块提供了import语句接口,不过这个模块在Python3.4已经deprecated了。建议使用importlib来处理。
`