dlfjj
dlfjj

Reputation: 349

How can I convert .txt file into a list python?

Within the .txt file:

[['Courtney fan', 'https://www.aaa.com', 'he is a good guy'], ['Courtney fan', 'https://www.bbb.com', 'Dave Butner', 'https://www.ccc.com', 'Austin']]

I tried this method, but it doesn't split properly:

with open("/Users/jj/Desktop/Courtney_fan.txt","r") as f:
       sd = f.read().split() 

How can I write this into a nested list in python?

Upvotes: 1

Views: 1501

Answers (3)

Daniel Lee
Daniel Lee

Reputation: 8021

You simply need to open the file and read it. json should do this for you. What have you tried? And why didn't it work?

import json

with open(".txt") as f:
    l = json.load(f)

Upvotes: 0

Benjamin Mohn
Benjamin Mohn

Reputation: 301

As your .txt file appears to be correct formatted and ist read in as a string the build in function eval() does this for you.

Here an example which is similar to your string in the txt-file:

test = "['a', ['b','c']]"
>>> trial = eval(test)
>>> type(trial)
<class 'list'>
>>> trial
['a', ['b', 'c']]

For you it would then be:

with open("/Users/jj/Desktop/Courtney_fan.txt") as f:
       sd = f.read()

sd_list = eval(sd)

Upvotes: 0

DBrowne
DBrowne

Reputation: 703

If the data is a valid python literal (list, dict etc..) you can use the literal_eval function from pythons built-in ast package. This is better than a solution using eval as it will only evaluate a valid data structure, and does not allow arbitrary code execution. There are almost zero cases where using plain eval is a good idea.

from ast import literal_eval

with open("/Users/jj/Desktop/Courtney_fan.txt","r") as f:
    my_list = literal_eval(f.read())

Upvotes: 5

Related Questions