python将值加载到txt文件中的变量

时间:2017-12-11 07:57:54

标签: python

txt文件如下所示:

a.txt
['a','b','c']   #single line txt file

我想要做的是,在Python命令行中:

>> f = open('a.txt','r')
>> a = f.readline()  # want to put the list in to a, same as "a = ['a','b','c']"

我该怎么办? 蟒蛇新手,不能想到一个想法。

提前致谢!

1 个答案:

答案 0 :(得分:0)

这假设您在文件中有这个...“a b c”:

>>f = open('a.txt','r')
>> a = f.readline()  # want to put the list in to a, same as "a = ['a','b','c']"
>>#add this, it splits your input into array
>>a = a.split(" ")

这假设你在文件中有这个...“['a','b','c']”: 这样做

>>f = open('a.txt','r')
>> a = f.readline()  # want to put the list in to a, same as "a = ['a','b','c']"
>>#add this, it splits your input into array
>>a = a[1:len(a)-1]
>>a = a.split(",")