-3

I'm currently learning Python and I'm having an issue with getting integer values from a text file (myfile.config). My goal is to be able to read a text file, find the integers then assign the said integers to some variables.

This is what my text file looks like (myFile.config):

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

This is what I've written so far:

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]

One of the issues which I've noticed so far (if my current understanding of Python is correct) is that the elements in the list are being stored as strings. I've tried to correct this by converting the list to an array via the NumPy library, but it hasn't worked.

Thank you for taking the time to read this question.

Sigma2n
  • 1
  • 5

3 Answers3

0

You have to call int for the conversion and I would use a dictionary for the result.

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

Now there's no need to create single variables like someValue or anotherValue. If you call the function with config = read_config() you have the values available as config['someValue'] and config['anotherValue'].

This is a much more flexible approach. Your current code will fail if you change the order of the lines in the configuration file. And if you add a fifth configuration entry you will have to change your code to create a new variable. The code in this answer can handle this by design.

Matthias
  • 12,873
  • 6
  • 42
  • 48
0

You can use float() or int() to turn strings into either float or integer. So in this case you can just type

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

or

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

seVenVo1d
  • 368
  • 2
  • 7
  • 16
0

With some eval magic, you get a dict out of the text file and if you insist, you can put them in the global namespace using globals()

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