Python - 从文本(配置)文件中获取整数
Python - Getting integers from a text (config) file
我目前正在学习 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 库将列表转换为数组来更正此问题,但没有奏效。
感谢您花时间阅读这个问题。
您必须调用 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
现在无需创建 someValue
或 anotherValue
等单个变量。如果您使用 config = read_config()
调用该函数,您将获得可用的值 config['someValue']
和 config['anotherValue']
.
这是一种更加灵活的方法。如果您更改配置文件中行的顺序,您当前的代码将失败。如果添加第五个配置条目,则必须更改代码以创建新变量。此答案中的代码可以通过设计处理此问题。
您可以使用 float()
或 int()
将字符串转换为浮点数或整数。所以在这种情况下你可以输入
tempConfig.append(float(fields[1]))
或
tempConfig.append(int(fields[1]))
借助一些 eval
魔法,您可以从文本文件中获取字典,如果您坚持,可以使用 globals()
将它们放入全局命名空间
def read_config():
config = '{' + open('myFile.config', 'r').read() + '}'
globals().update(eval(config.replace('{', '{"').replace(':', '":').replace('\n', ',"')))
我目前正在学习 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 库将列表转换为数组来更正此问题,但没有奏效。
感谢您花时间阅读这个问题。
您必须调用 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
现在无需创建 someValue
或 anotherValue
等单个变量。如果您使用 config = read_config()
调用该函数,您将获得可用的值 config['someValue']
和 config['anotherValue']
.
这是一种更加灵活的方法。如果您更改配置文件中行的顺序,您当前的代码将失败。如果添加第五个配置条目,则必须更改代码以创建新变量。此答案中的代码可以通过设计处理此问题。
您可以使用 float()
或 int()
将字符串转换为浮点数或整数。所以在这种情况下你可以输入
tempConfig.append(float(fields[1]))
或
tempConfig.append(int(fields[1]))
借助一些 eval
魔法,您可以从文本文件中获取字典,如果您坚持,可以使用 globals()
def read_config():
config = '{' + open('myFile.config', 'r').read() + '}'
globals().update(eval(config.replace('{', '{"').replace(':', '":').replace('\n', ',"')))