0

Hi there I want to add a file to python with a few diffrent list in it like

 File.txt:  
 ListA=1,2,3,4 ListB=2,3,4

I want to save the list in my script with the same name like in the File.txt. For example: ListA=[1,2,3,4] ListB=[2,3,4] After that I want to copy one list to a new list called for example li that I can use it. Here is my Script which dont work that u can see what I mean.

So 1st of all: How can I read lists from a txt file and use their name? 2nd How do I copy a specific list to a new list? Hope someone can help me :) And I hope it have not allready been asked.

def hinzu():
    #file=input('text.txt')
    f=open('text.txt','r')
    **=f.read().split(',')  
    print ('li',**)
    #this give me the output **=['ListA=1','2','3','4'] but actualy I want ListA=['1','2'...] 

def liste():
    total=1
    li=input('which list do you want to use?')
    for x in li:
        float(x)
        total *= x
    print('ende', total)
2
  • Why do you want to do it this way? Why not just use a dictionary, where the list names are the keys and the lists themselves are the values? Commented Jul 14, 2017 at 8:40
  • Where did File.txt come from? This feels like an XY problem. If possible, generate the file with a script and use pickle to store the lists directly Commented Jul 14, 2017 at 8:46

2 Answers 2

1

You need to split the text by = sign which will seprate the list name with list contents then split the content by ,

f=open('text.txt','r')
a,b=f.read().split('=')  
print (a,list(b.split(','))
Sign up to request clarification or add additional context in comments.

Comments

0

Split your input first by =, then by ,:

name, list = f.read().split('=')
list = list.split(',')

You may want to add another .split() for your ListB.

To set the name as a variable in the global name scope you can use:

globals().update({name:list})

Comments

Your Answer

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