【问题标题】:Python - Getting integers from a text (config) file [duplicate]Python - 从文本(配置)文件中获取整数
【发布时间】:2021-05-20 20:30:43
【问题描述】:

我目前正在学习 Python,但在从文本文件 (myfile.config) 中获取整数值时遇到了问题。我的目标是能够读取文本文件,找到整数,然后将所述整数分配给一些变量。

这是我的文本文件(myFile.config)的样子:

someValue:100
anotherValue:1000
yetAnotherValue:-5
someOtherValueHere:5

这是我目前写的:

import os.path
import numpy as np

# Check if config exists, otherwise generate a config file
def checkConfig():
    if os.path.isfile('myFile.config'):
        return True
    else:
        print("Config file not found - Generating default config...")
        configFile = open("myFile.config", "w+")
        configFile.write("someValue:100\rnotherValue:1000\ryetAnotherValue:-5\rsomeOtherValueHere:5")
        configFile.close()

# Read the config file
def readConfig():
    tempConfig = []
    configFile = open('myFile.config', 'r')
    for line in configFile:
        cleanedField = line.strip()  # remove \n from elements in list
        fields = cleanedField.split(":")
        tempConfig.append(fields[1])
    configFile.close()

    print(str(tempConfig))

    return tempConfig

configOutput = np.asarray(readConfig())

someValue = configOutput[0]
anotherValue = configOutput[1]
yetAnotherValue = configOutput[2]
someOtherValueHere = configOutput[3]

到目前为止,我注意到的一个问题(如果我目前对 Python 的理解是正确的)是列表中的元素被存储为字符串。我尝试通过 NumPy 库将列表转换为数组来纠正此问题,但没有成功。

感谢您抽出宝贵时间阅读此问题。

【问题讨论】:

  • 您已经有一个应该执行此操作的函数,但您没有使用它。 (现在您已将其删除)
  • @mkrieger1 我试过使用那个功能,但它不起作用。

标签: python arrays file-io


【解决方案1】:

您可以使用float()int() 将字符串转换为浮点数或整数。所以在这种情况下,您只需键入

tempConfig.append(float(fields[1]))

tempConfig.append(int(fields[1]))

【讨论】:

  • 哇,这太简单了 - 非常感谢。
【解决方案2】:

您必须调用 int 进行转换,我会使用字典来获取结果。

def read_config():
    configuration = {}
    with open('myFile.config', 'r') as config_file:
        for line in config_file:
            fields = line.split(':')
            if len(fields) == 2:
                configuration[fields[0].strip()] = int(fields[1])
    print(configuration)  # for debugging
    return configuration

现在无需创建像 someValueanotherValue 这样的单个变量。如果您使用config = read_config() 调用该函数,您将获得config['someValue']config['anotherValue'] 的值。

这是一种更灵活的方法。如果您更改配置文件中行的顺序,您当前的代码将失败。如果您添加第五个配置条目,您将不得不更改代码以创建新变量。此答案中的代码可以通过设计处理此问题。

【讨论】:

    【解决方案3】:

    使用一些eval 魔法,您可以从文本文件中获得一个字典,如果您坚持,您可以使用globals() 将它们放入全局命名空间中

    def read_config():
        config = '{' + open('myFile.config', 'r').read() + '}'
        globals().update(eval(config.replace('{', '{"').replace(':', '":').replace('\n', ',"')))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多