Python3 OS
os 模块的目录操作、路径处理、环境变量与 os.path 常用方法。
os 模块的常用功能
os talks to the operating system: create and remove directories, list them, rename, and query the working directory. os.makedirs creates parents recursively and os.removedirs removes them.
import os
import tempfile
root = tempfile.mkdtemp()
sub = os.path.join(root, 'a', 'b')
os.makedirs(sub)
print(os.path.isdir(sub))
print(sorted(os.listdir(root)))
print(os.getcwd() != '')
os.rename(os.path.join(root, 'a'), os.path.join(root, 'c'))
print(sorted(os.listdir(root)))True
['a']
True
['c']路径操作
Never concatenate paths by hand — a literal / breaks on Windows. os.path.join picks the platform separator, os.path.split separates directory and name, splitext separates the extension.
import os
p = os.path.join('data', 'sub', 'file.tar.gz')
print(p)
print(os.path.split(p))
print(os.path.splitext(p))
print(os.path.basename(p), os.path.dirname(p))
print(os.path.sep == os.sep)data\sub\file.tar.gz
('data\\sub', 'file.tar.gz')
('data\\sub\\file.tar', '.gz')
file.tar.gz data\sub
True/ instead. That is exactly why you should use os.path.join.目录遍历
os.walk(top) traverses a tree top-down, yielding (dirpath, dirnames, filenames) per level. Filter by extension inside the loop to find files of a kind.
import os
import tempfile
root = tempfile.mkdtemp()
os.makedirs(os.path.join(root, 'sub'))
for name in ('a.py', 'b.txt', os.path.join('sub', 'c.py')):
open(os.path.join(root, name), 'w').close()
found = []
for dirpath, dirnames, filenames in os.walk(root):
for fn in filenames:
if fn.endswith('.py'):
found.append(os.path.relpath(os.path.join(dirpath, fn), root))
print(sorted(found))
print(len(found))['a.py', 'sub\\c.py']
2环境变量
os.environ is the environment mapping; os.environ.get(k, default) is the safe read, and os.getenv is equivalent. Changes affect only this process and its children, never the system.
import os
print('PATH' in os.environ)
print(os.environ.get('NOT_SET_XYZ', 'fallback'))
os.environ['MY_VAR'] = '1'
print(os.getenv('MY_VAR'))
del os.environ['MY_VAR']
print(os.getenv('MY_VAR', 'gone'))True
fallback
1
goneos.path 常用方法
exists tests presence, isfile/isdir test type, getsize returns bytes, abspath makes it absolute and normpath normalises. They have no side effects, so they are safe in conditions.
import os
import tempfile
root = tempfile.mkdtemp()
p = os.path.join(root, 'x.txt')
with open(p, 'w', encoding='utf-8') as f:
f.write('12345')
print(os.path.exists(p), os.path.isfile(p), os.path.isdir(p))
print(os.path.getsize(p))
print(os.path.isabs(p), os.path.isabs(os.path.abspath(p)))
print(os.path.normpath('a/./b/../c'))True True False
5
True True
a\cos 模块的常用功能
os 提供与操作系统交互的接口:创建/删除目录、列目录、重命名、获取当前工作目录。os.makedirs 会递归创建父目录,os.removedirs 反之。
import os
import tempfile
root = tempfile.mkdtemp()
sub = os.path.join(root, 'a', 'b')
os.makedirs(sub)
print(os.path.isdir(sub))
print(sorted(os.listdir(root)))
print(os.getcwd() != '')
os.rename(os.path.join(root, 'a'), os.path.join(root, 'c'))
print(sorted(os.listdir(root)))True
['a']
True
['c']路径操作
不要用字符串拼路径 —— 手写 / 在 Windows 上会出问题。os.path.join 按平台自动选分隔符,os.path.split 拆目录与文件名,splitext 拆扩展名。
import os
p = os.path.join('data', 'sub', 'file.tar.gz')
print(p)
print(os.path.split(p))
print(os.path.splitext(p))
print(os.path.basename(p), os.path.dirname(p))
print(os.path.sep == os.sep)data\sub\file.tar.gz
('data\\sub', 'file.tar.gz')
('data\\sub\\file.tar', '.gz')
file.tar.gz data\sub
True/。这正是必须用 os.path.join 的原因。目录遍历
os.walk(top) 自顶向下遍历目录树,每次产出 (当前目录, 子目录列表, 文件列表)。要找某类文件,在循环里判断扩展名即可。
import os
import tempfile
root = tempfile.mkdtemp()
os.makedirs(os.path.join(root, 'sub'))
for name in ('a.py', 'b.txt', os.path.join('sub', 'c.py')):
open(os.path.join(root, name), 'w').close()
found = []
for dirpath, dirnames, filenames in os.walk(root):
for fn in filenames:
if fn.endswith('.py'):
found.append(os.path.relpath(os.path.join(dirpath, fn), root))
print(sorted(found))
print(len(found))['a.py', 'sub\\c.py']
2环境变量
os.environ 是环境变量的映射,os.environ.get(k, default) 读取更安全。os.getenv 等价。修改只影响当前进程及其子进程,不会写回系统。
import os
print('PATH' in os.environ)
print(os.environ.get('NOT_SET_XYZ', 'fallback'))
os.environ['MY_VAR'] = '1'
print(os.getenv('MY_VAR'))
del os.environ['MY_VAR']
print(os.getenv('MY_VAR', 'gone'))True
fallback
1
goneos.path 常用方法
exists 判断存在、isfile/isdir 判断类型、getsize 取字节数、abspath 转绝对路径、normpath 规范化。这些函数不做 I/O 之外的副作用,可以放心用于条件判断。
import os
import tempfile
root = tempfile.mkdtemp()
p = os.path.join(root, 'x.txt')
with open(p, 'w', encoding='utf-8') as f:
f.write('12345')
print(os.path.exists(p), os.path.isfile(p), os.path.isdir(p))
print(os.path.getsize(p))
print(os.path.isabs(p), os.path.isabs(os.path.abspath(p)))
print(os.path.normpath('a/./b/../c'))True True False
5
True True
a\c