【发布时间】: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 我试过使用那个功能,但它不起作用。