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

如何在Python中读取文本文件里Theme对应的值?

读取文本文件中Theme对应的值

你的文本文件内容如下:

Theme="dark_background"
Color="Blue"

基于你已有的读取整个文件的代码,这里提供几种提取Theme对应值的实用方法:

方法一:字符串分割处理

先将读取到的内容按行拆分,遍历每一行找到Theme开头的行,再通过字符串分割提取引号内的值:

with open("nxc.txt","r") as f:
    asz = f.read()

# 提取Theme对应的值
for line in asz.splitlines():
    if line.startswith('Theme='):
        theme_value = line.split('"')[1]
        print(theme_value)  # 输出 dark_background
        break

方法二:逐行读取(更高效)

不用一次性读取整个文件,直接逐行遍历,找到目标行后提取值,适合处理大文件:

with open("nxc.txt","r") as f:
    for line in f:
        line = line.strip()
        if line.startswith('Theme='):
            theme_value = line.split('"')[1]
            print(theme_value)
            break

方法三:正则表达式(适配复杂格式)

如果文件格式可能有变化(比如Theme前后有空格),用正则表达式匹配更灵活:

import re

with open("nxc.txt","r") as f:
    asz = f.read()

match_result = re.search(r'Theme\s*=\s*"([^"]+)"', asz)
if match_result:
    theme_value = match_result.group(1)
    print(theme_value)

内容的提问来源于stack exchange,提问作者Mohit Narwani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:01:43