You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python处理.cfg结构化数据的最优策略及文件访问方案咨询

Hey there! Reading your .cfg as a plain text file gets the job done, but since your data is structured as key-value pairs, parsing it into a dictionary will make accessing individual values way more intuitive and maintainable. Let’s walk through a few better approaches tailored to your use case:

1. Manual Parsing (No External Libraries)

This is a straightforward option if your .cfg format stays consistent (single line, key-value pairs separated by spaces, single-word values). We’ll split the content into tokens and map them to a dictionary, even converting numeric values to integers automatically:

config_data = {}

with open('info.cfg', 'r') as f:
    content = f.read().strip()
    # Split the content into individual key/value tokens
    tokens = content.split()
    # Iterate over tokens in pairs (key with colon, then value)
    for i in range(0, len(tokens), 2):
        key = tokens[i].rstrip(':')  # Remove the trailing colon from the key
        value = tokens[i+1]
        # Convert numeric values to integers for easier math/processing
        if value.isdigit():
            value = int(value)
        config_data[key] = value

# Access data with simple dictionary lookups
print(config_data['Name'])  # Output: ABC
print(config_data['Age'])   # Output: 50
2. Using Python’s Built-in configparser (For Scalable Configs)

If you might expand your .cfg file to include sections later (a common pattern for config files), the built-in configparser module is perfect. Since your current file lacks sections, we’ll temporarily add a dummy [DEFAULT] section to make it compatible:

from configparser import ConfigParser

config = ConfigParser()

# Read the file and prepend a dummy section header
with open('info.cfg', 'r') as f:
    modified_content = f"[DEFAULT]\n{f.read()}"
config.read_string(modified_content)

# Access values directly from the DEFAULT section
name = config['DEFAULT']['Name']
height = int(config['DEFAULT']['Height'])

print(name)    # Output: ABC
print(height)  # Output: 170

This method handles edge cases like quoted values (e.g., City: "San Francisco") automatically, making it future-proof if your config needs grow.

3. Regular Expressions (For Flexible Formatting)

If your .cfg file might have variations (like line breaks between key-value pairs or multi-word values), regex is a robust way to extract pairs regardless of whitespace:

import re

config_data = {}

with open('info.cfg', 'r') as f:
    content = f.read()
    # Regex pattern to match "Key: Value" pairs (works across lines too)
    pattern = r'(\w+):\s*(\S+)'
    matches = re.findall(pattern, content)
    
    for key, value in matches:
        if value.isdigit():
            value = int(value)
        config_data[key] = value

print(config_data['City'])  # Output: Cali

The pattern (\w+):\s*(\S+) matches any word as the key, followed by a colon, optional whitespace, and any non-whitespace sequence as the value—this works even if your key-value pairs are spread across multiple lines.

Which to Choose?

  • Stick with manual parsing if your config stays simple and consistent.
  • Use configparser if you plan to add sections or more complex values later.
  • Go with regex if you need flexibility for varying formatting.

内容的提问来源于stack exchange,提问作者Moon Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:00:45