- os.chdir() 函数用于改变当前工作目录到指定的路径。它接受一个字符串参数,该参数是要切换到的新目录的路径。
在这个示例中,os.chdir(“/path/to/new/directory”) 将当前工作目录更改为 “/path/to/new/directory”。
import os
# 当前工作目录
print("当前工作目录:", os.getcwd())
# 切换工作目录到指定路径
os.chdir("/path/to/new/directory")
# 打印切换后的工作目录
print("切换后的工作目录:", os.getcwd())
- ConfigParser() 函数在Python中是用来读取和解析配置文件的。它允许开发者从配置文件中读取配置信息,例如键值对,然后将其用于程序中。通常情况下,配置文件采用INI格式,它是一种简单的配置文件格式,由节(section)和选项(option)组成。
以下是一个示例,展示了如何使用ConfigParser读取和解析配置文件。
假设配置文件 config.ini 的内容如下:
[Server]
ip = 192.168.1.100
port = 8080
[Credentials]
username = user123
password = secret_password
import configparser
# 创建一个ConfigParser对象
config = configparser.ConfigParser()
# 从文件中读取配置信息
config.read('config.ini')
# 获取特定节(section)下的选项(option)的值
server_ip = config.get('Server', 'ip')
port = config.getint('Server', 'port')
username = config.get('Credentials', 'username')
password = config.get('Credentials', 'password')
# 使用获取到的配置信息
print(f"Connecting to {server_ip}:{port} with username '{username}' and password '{password}'")
- OrderedDict 是 Python 标准库 collections 模块中的一个数据结构,它是一个有序字典,可以按元素插入的顺序来迭代。
OrderedDict 与普通字典的区别在于它记住了元素被插入的顺序。这意味着当你迭代 OrderedDict 时,元素的顺序将与它们被插入时的顺序相同。
以下是一个使用 OrderedDict 的示例:
from collections import OrderedDict
# 创建一个空的有序字典
ordered_dict = OrderedDict()
# 向有序字典中添加键值对
ordered_dict['a'] = 1
ordered_dict['b'] = 2
ordered_dict['c'] = 3
# 输出有序字典
print(ordered_dict)
# 遍历有序字典
for key, value in ordered_dict.items():
print(key, value)
- 正则表达式
[A-Za-z_]: 匹配任何大小写字母或下划线
\w*: 匹配零个或多个字母、数字或下划线
import re
# 定义正则表达式模式
NAME_RE = r"[A-Za-z_]\w*"
# 要匹配的字符串
text = "变量名: my_variable, 函数名: some_function, 无效的名称: 123abc"
# 查找匹配项
matches = re.findall(NAME_RE, text)
# 输出匹配结果
print(matches)