阅读符号后

时间:2015-05-20 04:26:23

标签: python-3.x file-io

假设一个包含" i = 1"的文本文件,我想阅读" 1"并将其分配给某个变量。那么我怎么能忽略,直到等号然后检索数字?

1 个答案:

答案 0 :(得分:0)

如果文本文件的格式类似于python文件,则可以使用exec("file contents")甚至import文件。大多数人因为它的漏洞而对exec()感到不满:除非你自己编写代码,否则你不知道你运行的代码是什么。

如果您是将变量放入文件的人,那么我强烈建议您查看pickle。它允许您将python对象和“dump”它们放入一个文件中供以后检索 - 您可以创建一个具有self.i = 1等属性的对象,并且它将在运行中保留。

直接回答您的问题:

#assuming only variables formatted as "variable = value" in file
#assuming only one variable per line
variables = { }
with open("my_variables.txt", "r") as f:
    #iterates through each line
    for line in f:
        #for each line, splits it at the '=' into two parts
        # and gets first half (before the '=') and strips it of any spaces
        # before or after it the variable, then stores it as 'name'
        name = line.split("=")[0].strip()
        #gets second half and stores it as 'value' the same way
        value = line.split("=")[1].strip()
        #if the values are always integers you can convert them
        # from strings to integers:
        value = int(value)
        #stores both variable name and value into the 'variables' dictionary
        variables[name] = value
print(variables) # prints { 'i' : '1' }