Python-从文本(配置)文件获取整数
我目前正在学习Python,在从文本文件(myfile.config)获取整数值时遇到了一个问题。我的目标是能够读取文本文件,找到整数,然后将所述整数分配给一些变量 这是我的文本文件(myFile.config)的外观: 这是我到目前为止写的:Python-从文本(配置)文件获取整数,python,arrays,file-io,Python,Arrays,File Io,我目前正在学习Python,在从文本文件(myfile.config)获取整数值时遇到了一个问题。我的目标是能够读取文本文件,找到整数,然后将所述整数分配给一些变量 这是我的文本文件(myFile.config)的外观: 这是我到目前为止写的: import os.path import numpy as np # Check if config exists, otherwise generate a config file def checkConfig(): if os.path
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\u config()
调用函数,则可以使用config['someValue']
和config['anotherValue']
等值
这是一种更加灵活的方法。如果更改配置文件中的行顺序,则当前代码将失败。如果添加第五个配置条目,则必须更改代码以创建新变量。此答案中的代码可以通过设计处理此问题。您可以使用float()
或int()
将字符串转换为float或整数。所以在这种情况下,你只需输入
tempConfig.append(float(字段[1]))
或
tempConfig.append(int(字段[1])
使用一些eval
magic,您可以从文本文件中获得一个dict,如果您坚持,您可以使用globals()
你已经有了一个函数,应该用来做这件事,但你没有使用它。(现在你已经删除了它)@mkrieger1我试过使用这个函数,但它就是不起作用。哇,那太简单了——非常感谢你。
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
def read_config():
config = '{' + open('myFile.config', 'r').read() + '}'
globals().update(eval(config.replace('{', '{"').replace(':', '":').replace('\n', ',"')))