【问题标题】:python read data from file and put values into variablespython从文件中读取数据并将值放入变量中
【发布时间】:2018-07-10 02:04:12
【问题描述】:

嘿 stackoverflow 我需要帮助解决这个问题。我希望能够读取格式如下的文本文件:

test: value1
test2: value2
test3(sometimes included): value3

test: value1
test2: value2

test: value1
test2: value2
test3(sometimes included): value3

您会看到 test3 有时包含在文件中,我希望能够读取它,但不希望它与文件中的其他值混淆。

为了完全清楚,我希望能够在 python 中读取文件并将变量的值放入 python 中的字符串中。

这是我目前所拥有的(这不是我想要的,因为如果该行没有 test3,它会与其他值混淆)

file = open("output.txt").readlines()

with line in file:
    if "test3" in line:
        test = find_between(...)
        test2 = find_between(...)
        test3 = find_between(...)
        ... 

【问题讨论】:

    标签: python python-2.7 file text


    【解决方案1】:

    我认为您需要 re.split,代码如下。

    重新导入

    with open("output.txt", "r") as f:

        for line in f:
            if "test3" not in line:
                continue
    
            items = re.split("[\(\)]", line)
            if len(items) > 1:
                print(items[1])
    

    【讨论】:

    • 不幸的是,这对我不起作用我不明白你为什么要拆分这些反斜杠。
    • 请忽略反斜杠,我的意思是逃避,:(
    • 我设法解决了我的问题,使用 re.findall :) 你让我走上了正确的道路,谢谢
    【解决方案2】:

    由于test 和test2 始终存在,因此不应将它们放入条件块中。另请注意,由于test3 是可选的,因此最好使用None 对其进行初始化,然后在用于某些用途时测试它是否不是None。

    file = open("output.txt").readlines()
    
    with line in file:
        test = find_between(...)
        test2 = find_between(...)
        test3 = None
        if "test3" in line:
            test3 = find_between(...)
        ...
        if test3 is not None:
            do_something(test3)
    

    【讨论】:

    • 是的,它可以工作,但我想将它们中的每一个都添加到一个块中,以便以后使用。例如 test1,test2,test3,我希望能够同时使用 test1 和 test3 的值。这就是我在它们之间添加空格的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多