做技术一定要一颗恒心,这样才不会半途而废。
目录
上一节我们介绍了文件相关的操作,本节我们来介绍目录相关的操作。
1,os 模块
os 模块是Python 中的内建模块,该模块中包含许多系统相关的操作。我们要介绍的目录相关的操作,也都包含在该模块中。
我们可以使用dir(os) 来查看该模块中所有属性和函数,共有几百个属性和函数。这里我们只介绍一部分函数,可以使用help(os.函数名) 来查看某个函数的帮助手册。
os.linesep:获取当前系统的行的换行符。
os.getcwd():获取当前工作目录。
os.listdir(path=None):列出path 路径中的所有文件和目录。path 为None 时,表示当前目录。
os.path.abspath(path):获取path 的绝对路径。
os.path.isfile(path):判断path 是否是一个文件。
os.path.isdir(path):如果path 存在且为目录,则返回True,否则返回False。
os.path.isabs(path):判断path 是否是一个绝对路径。
os.path.exists(path):判断path 是否存在。
os.path.split(file):返回file 的路径名与文件名,返回值是一个元组。
os.path.splitext(file):返回file 的路径与扩展名,返回值是一个元组。
os.path.dirname(path):返回path的目录 。
os.path.basename(path):返回path 的文件名。
os.rename(old, new): 将文件或目录old 重命名为new。
os.mkdir(dir):创建目录,dir 只能是单级目录。
os.makedirs(dir):创建目录,dir 可以是单级目录,也可以是多级目录 。
os.rmdir(dir):删除目录,dir 只能是空目录,否则抛出异常。
os.remove(path):删除文件,如果出现错误将抛出异常。
os.removedirs(path):删除目录,且该目录中不能有其它文件或目录,也就是该目录必须为空,否则将出现异常。
os.stat(path):获取文件或目录的状态信息,比如创建时间,大小等。其返回值为os.stat_result类型。
os.path.getsize(file):返回file 的大小 。
os.chmod(file):修改file 的访问权限。
os.chdir(path):从当前目录切换到目录path。
2,shutil 模块
shutil 模块主要是用来操作文件和目录的。
我们可以使用help(shutil) 查看该模块的帮助文档,使用dir(shutil) 查看其支持的所有类,属性和方法。
>>> dir(shutil)
['Error', 'ExecError', 'ReadError',
'RegistryError', 'SameFileError',
'SpecialFileError', '_ARCHIVE_FORMATS',
'_BZ2_SUPPORTED', '_LZMA_SUPPORTED',
'_UNPACK_FORMATS', '_ZLIB_SUPPORTED',
'__all__', '__builtins__', '__cached__',
'__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__',
'_basename', '_check_unpack_options',
'_copyxattr', '_destinsrc',
'_ensure_directory', '_find_unpack_format',
'_get_gid', '_get_uid', '_make_tarball',
'_make_zipfile', '_ntuple_diskusage',
'_rmtree_safe_fd', '_rmtree_unsafe',
'_samefile', '_unpack_tarfile',
'_unpack_zipfile', '_use_fd_functions',
'chown', 'collections', 'copy', 'copy2',
'copyfile', 'copyfileobj', 'copymode',
'copystat', 'copytree', 'disk_usage',
'errno', 'fnmatch', 'get_archive_formats',
'get_terminal_size', 'get_unpack_formats',
'getgrnam', 'getpwnam', 'ignore_patterns',
'make_archive', 'move', 'os',
'register_archive_format',
'register_unpack_format',
'rmtree', 'stat', 'sys', 'unpack_archive',
'unregister_archive_format',
'unregister_unpack_format', 'which']
这里是该模块的官方文档,本节中我们只介绍少数几个操作,其它函数的用法,可参考其官方文档。
shutil.copyfile(oldfile, newfile):将文件oldfile复制一份到newfile。
shutil.copy(oldfile, new):将文件oldfile复制一份到new,返回新的文件名。new 可以是文件,也可以是目录。
shutil.copytree(olddir, newdir):将整个目录olddir,递归拷贝到newdir。
shutil.move(src, dst):将src 移动到dst。
shutil.rmtree(dir):删除整个目录树dir。
(完。)
推荐阅读:
欢迎关注作者公众号,获取更多技术干货。