Python-os:操作系统接口模块

该模块提供了一些方便使用操作系统相关功能的函数。
官方文档-os部分
python3.7os源码地址

os.getenv(key, default=None)¶

如果存在,返回环境变量 key 的值,否则返回 default。 key , default 和返回值均为 str 字符串类型。

在Unix系统上,键和值会使用 sys.getfilesystemencoding() 和'surrogateescape' 错误处理进行解码。如果你想使用其他的编码,使用 os.getenvb()。

可用性: 大部分的Unix系统,Windows。
效果同 os.environ.get()
eg. os.getenv(“path”)

环境变量用途

比如数据库密码不宜明文写进代码里,可以写进自己本机的环境变量里,程序用的时候通过os.environ.get()调用。开发环境用自己的,生产环境用另一套,方便且安全。

os.walk(top, topdown=True, οnerrοr=None, followlinks=False)

通过自上而下或自下而上遍历目录树来生成目录树中的文件名。对于树中以目录top为根的每个目录(包括top本身),它生成一个3元组(dirpath,dirname,filename)。

dirpath是一个字符串,即目录的路径。dirnames是dirpath中的子目录的名称列表(不包括‘…'和‘.’)。filenames是dirpath中非目录文件的名称列表。请注意,列表中的名称不包含路径组件。要获取dirpath中文件或目录的完整路径(以top开头),请执行os.path.join(dirpath,name)。

如果可选参数topdown为True或未指定,则在其任何子目录的三元组之前生成目录的三元组(目录是自上而下生成的)。如果topdown为false,则在其所有子目录的三元组之后生成目录的三元组(目录是自下而上生成的)。无论topdown的值如何,都会在生成目录及其子目录的元组之前检索子目录列表。

当topdown为True时,调用者可以就地修改dirnames列表(可能使用del或slice赋值),walk()只递归到名称保留在dirnames中的子目录;这可以用来删减搜索,强加特定的访问顺序,甚至在再次恢复walk()之前通知walk()调用者创建或重命名的目录。当topdown为false时修改dirname对遍历的行为没有影响,因为在自底向上模式中,dirname中的目录是在dirpath本身生成之前生成的。

默认情况下,将忽略来自scandir()调用的错误。如果指定了可选参数onerror,它应该是一个函数;它将用一个参数调用,即OSError实例。它可以报告错误以继续执行漫游,也可以引发异常以中止漫游。请注意,filename可用作异常对象的filename属性

默认情况下,walk()不会进入解析到目录的符号链接。将Follow Links设置为True可在支持symlink的系统上访问symlink指向的目录。

This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory:

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print(root, "consumes", end=" ")
    print(sum(getsize(join(root, name)) for name in files), end=" ")
    print("bytes in", len(files), "non-directory files")
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

In the next example (simple implementation of shutil.rmtree()), walking the tree bottom-up is essential, rmdir() doesn’t allow deleting a directory before the directory is empty:

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

os.path-常见路径操作官方文档

os.path.join(path, *paths)

Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

On Windows, the drive letter is not reset when an absolute path component (e.g., r’\foo’) is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join(“c:”, “foo”) represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

os.path.abspath(path)

Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值