os
os模块提供了与操作系统交互的功能,能够处理操作系统相关的底层操作。这应该是比较的内置模块了,感觉它用法挺多的,整理一下挺好的。
(以下都是问的深度求索,哈哈)
文件和目录操作
1
2
3
4
5
6
7
8
9
10
11
12
13
| import os
# 创建目录
os.mkdir("new_folder")
os.makdirs("parent/child/grandchild", exist_ok=True) # 避免目录存在时报错
# 删除目录或文件
os.rmdir("empty_folder")
os.remove("old_file.txt")
# 遍历目录内容
for file in os.listdir("."):
print(file)
|
路径管理(os.path
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| import os
# 路径拼接
path = os.path.join("folder", "subfolder", "file.txt")
# 获取绝对路径
abs_path = os.path.abspath("file.txt")
# 检查是否存在
if os.path.exists("data.txt")
pass
# 分离文件名和扩展民
filename, ext = os.path.splitext("image.jpg")
|
系统信息
1
2
3
4
5
6
7
| import os
# 获取当前工作目录
cwd = os.getcwd()
# 获取操作系统类型
print(os.name) # 'posix'(Linux/macOS)或 'nt'(Windows)
|
环境变量管理
1
2
3
4
5
6
7
8
| import os
# 获取环境变量
home_dir = os.environ.get("HOME")
path_var = os.environ.get("PATH")
# 设置环境变量(仅在当前进程生效)
os.evrion["MY_VAR"] = "123"
|
执行系统命令
1
2
3
4
| import os
os.system("ls -l") # Linux/macOS
os.system("dir") # Windows
|
sys
sys模块提供与python解释器和运行时环境交互的功能
(以下也都是问的深度求索)
获取命令行参数
1
2
3
4
5
6
| import sys
# 运行脚本时传递参数:python script.py arg1 arg2
script_name = sys.argv[0]
first_arg = sys.argv[1]
second_arg = sys.argv[2]
|
强制退出程序
1
2
3
4
5
6
| import sys
if some_errora_condition:
sys.exit("程序异常终止") # 退出并返回错误信息(状态码默认为1)
sys.exit(0) # 正常退出,状态码0表示成功
|
重定向标准输出/错误
1
2
3
4
5
6
7
8
9
10
11
12
| import sys
with open("output.txt", "w") as f:
sys.stdout = f # 输出重定向到文件f
print("这条信息会写入文件")
# 恢复默认输出(控制台)
sys.stdout = sys.__stdout__
print("这条信息显示在控制台")
# 捕获错误信息
sys.stderr.write("这是一条错误消息\n")
|
模块搜索路径管理
1
2
3
4
5
6
7
| import sys
# 添加自定义路径到模块搜索路径
sys.path.append("/path/to/my/modules")
# 查看当前搜索路径
print("模块搜索路径", sys.path)
|
获取系统信息
1
2
3
4
5
6
7
| import sys
print("操作系统平台:", sys.platform)
print("python版本:", sys.version)
print("默认编码:", sys.getdefaultencoding()) # 默认utf-8
|
获取递归深度
1
2
3
4
5
6
7
| import sys
# 获取当前递归深度限制
print("递归深度限制:", sys.getrecursionlimit())
# 设置新的递归深度(谨慎使用!)
sys.setrecursionlimit(4000)
|
pathlib
- 内置模块
- 用于处理文件和目录
- 跨平台,适用于不同的操作系统
1
2
3
4
5
6
7
8
9
| from pathlib import Path
Path.cwd() # 当前目录
Path.home() # 用户目录
# 目录拼接
Path(Path.home(), "Desktop")
Path.joinpath(Path.home(), "Desktop")
Path.cwd() / "temp"
|
路径信息获取
1
2
3
4
5
6
7
8
9
10
11
12
13
| from pathlib import Path
my_path = Path(r"c:\User\lreverse\Desktop\temp")
my_path.name # 文件名+后缀
my_path.stem # 文件名
my_path.suffix # 后缀
my_path.suffixes # 后缀列表
my_path.root # 根目录
my_path.parts # 路径上的文件部分
my_path.parent # 父级目录
my_path.resolve() # 获取绝对路径
|
路径判断
1
2
3
4
5
6
7
8
9
| from pathlib import Path
my_path = Path(r"c:\User\lreverse\Desktop\temp")
if my_path.exists(): # 判断路径是否存在
if my_path.is_file(): # 判断是否为文件
pass
elif my_path.is_dir(): # 判断是否为目录
pass
|
路径建立、删除
1
2
3
| Path.mkdir() # 创建文件
Path.rmdir() # 删除文件夹(文件夹必须为空
Path.unlink() # 删除文件
|
处理json数据
性能:orjson
(Rust) > ujson
(C) > json
(标准库)
orjson
原生支持datetime
/UUID
/numpy
,无需额外处理
json
1
2
3
4
5
6
7
8
9
10
11
12
13
| import json
data = [{'name': 'bob', 'age': 30}, {'name': 'alice', 'age': 25}]
json_str = json.dumps(data, indent=2)
load_data = json.loads(json_str)
with open('data.json', 'w') as f:
json.dump(data, f, indent=2)
with open('data.json', 'r') as f:
load_data = json.load(f)
|
ujson
ujson
曾多次曝出安全漏洞
1
2
3
4
5
6
| import ujson
data = [{'name': 'bob', 'age': 30}, {'name': 'alice', 'age': 25}]
json_str = ujson.dumps(data)
load_data = ujson.loads(json_str)
|
orjson
序列化成字节流
1
2
3
4
5
6
7
| import orjson
from datetime import datetime
data = [{'name': 'bob', 'age': 30, 'time': datetime.utcnow()}, {'name': 'alice', 'age': 25, 'time': datetime.utcnow()}]
json_str = orjson.dumps(data) # 时间戳自动转为字符串
load_data = orjson.loads(json_str)
|
处理时间
datetime
1
2
3
4
5
6
7
8
9
10
11
12
| from datetime import datetime
# 日期时间对象
now = datetime.now()
utcnow = datetime.utcnow()
# 格式化成字符串
formatted = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 时间戳转换
timestamp = now.timestamp()
from_timestamp = datetime.fromtimestamp(timestamp)
|
time
底层时间操作
1
2
3
4
5
6
7
| import time
# 获取时间戳(从1970-01-01 00:00:00 UTC开始的秒数)
timestamp = time.time()
# 休眠
time.sleep(2) # 秒
|
arrow