Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file as a list in python

Most pythonic way to import a raw string from a txt file into a list? contents of "file.txt" looks like this (all in a single line):

["string1","anotha one","more text","foo","2the","bar","fin"]

I could easily copy/paste the string into my script but am sure there is a more dynamic method.

In basic pseudocode:

my_list = *contents of file.txt*
like image 628
jnard0ne Avatar asked Sep 10 '26 02:09

jnard0ne


1 Answers

Read it as json

import json
with open('file.txt', 'r') as list_file:
    my_list = json.load(list_file)

print (my_list)

Output should be

['string1', 'anotha one', 'more text', 'foo', '2the', 'bar', 'fin']

like image 119
smac89 Avatar answered Sep 11 '26 15:09

smac89