How to read just lists in a text file in Python? -
i need read text file this
bruce chung bruce@outlook.com 8893243 costarricense divisa del informe colones ['nokia', 5277100.0, 'china'] ['samsung', 10554200.0, 'turkey'] ['apple', 52771000.0, 'argentina']
but need read lists inside file , assign them new variable.
i've used this
data =[ast.literal_eval(x) x in open("test.txt")] registros = data
and worked before until added information of user below.
is there way read lists in text?
you can use str.startswith()
check if string starts '['
, , use ast.literal_eval()
if true. example -
with open("test.txt") f: registros = [ast.literal_eval(x) x in f if x.startswith('[')]
demo -
>>> s = """bruce ... chung ... bruce@outlook.com ... 8893243 ... costarricense ... divisa del informe colones ... ['nokia', 5277100.0, 'china'] ... ['samsung', 10554200.0, 'turkey'] ... ['apple', 52771000.0, 'argentina']""".splitlines() >>> import ast >>> registros = [ast.literal_eval(x) x in s if x.startswith('[')] >>> registros [['nokia', 5277100.0, 'china'], ['samsung', 10554200.0, 'turkey'], ['apple', 52771000.0, 'argentina']]
for updated requirements in comments -
how can read user info , assign variable using method?
assuming line not list, part of user info
you can use simple loop, keep appending variable if line not start '['
, , if does, use ast.literal_eval()
on it, , append registros
list.
example -
import ast open("test.txt") f: user_info = '' registros = [] line in f: if line.startswith('['): registros.append(ast.literal_eval(line)) else: user_info += line
if user_info 6 lines (as given in comments) , can use -
import ast open("test.txt") f: user_info = '' i,line in enumerate(f): user_info += line if i==5: break registros = [ast.literal_eval(x) x in f if x.startswith('[')]
Comments
Post a Comment