Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have placed a list in a text file. I want python to read the text file and return the contents as a list. However, it is instead reading the content as a string:

Text file:

['a','b','c']

Python:

ids=[]

writtenFile =open('file.txt')
readFile=writtenFile.read()
ids= readFile
writtenFile.close()
print ids 

What is returned is ['a','b','c'] as a string, not as a list or just text. Is there a way I can retrieve ['a','b','c'] from the text file and then store this in the ids string so that ids is a list ['a','b','c'] and not the string ? "['a','b','c']"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
248 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use ast.literal_eval to literally evaluate the contents of file as is written though really a string:

data = ast.literal_eval(open('data.txt').read()) # create file, read contents, evaluate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...