简体   繁体   中英

Python: Read file with list as list

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']"?

使用ast.literal_eval从字面上评估实际上是字符串编写的文件内容:

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

If you just have the same format the quickest way would be just to strip and split:

with open('file.txt') as f:
    print(f.readline().translate(None,"'[]\n").split(","))
    ['a', 'b', 'c']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM