1

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?

3
  • [Python]: json.loads() (after replacing ' by ")? Commented Sep 12, 2017 at 6:21
  • This looks like valid json. Just import the json module and use the load function within it. Commented Sep 12, 2017 at 6:22
  • It is already in the form of the list inside a text file. Check how to read txt file its simple. Read the input/output (i/o) documentation of python. Commented Sep 12, 2017 at 6:23

3 Answers 3

5

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())
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.