简体   繁体   中英

Read Python list from a Text file

I recently did a python code execution and on dumping common word from list to.txt file, the execution was failed and exception was caught up in except block. Now I only have the whole list, and copied it to a Text file.

All I want to do is read the list off.txt file and store it inside python list. When I copy all that from.txt, my python stops responding so all I can do is fetch from.txt file.

The list is in this format inside.txt file:

['abc.Android.Permission_A', 'abc.Android.Permission_B', .. up to 12000+ words]

Why do you want to use WordPad? It is much simpler with txt files or.py.

Probably this answer should be a comment, because I am not giving you the solution to read lists from a WordPad file, but I don't have enough reputation, so...

With.py file:

You can copy the list in a.py file, for example named mylist.py:

my_list = ['abc.Android.Permission_A', 'abc.Android.Permission_B', 'abc.Android.Permission_C', etc.. ]

And import it in your script:

from mylist import my_list

Then you can use it as a normal variable.

You can also directly initialize it in your script if your prefer to, in that case you don't need to import anything. The first command would suffice.

With.txt file :

text_file = open("my_list.txt", "r")
my_list = text_file.read().translate({ord(c): None for c in "[]'"}).split(','))
text_file.close()

Or you can use the ast library like Adam Smith mentioned in the comments:

import ast; 
text_file = open("my_list.txt", "r")
my_list = ast.literal_eval(text_file.read())
text_file.close()

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