1

How can I make a text file (STRnumbers.txt) that I have which has a long list of lists like this (one on each line):

['1', '2', '3']
['3', '3', '1']
['10', '1', '3']

Into one master list:

Master = [(1, 2, 3), (3, 3, 1), (10, 1, 3)]

And make the numbers into regular integers?

FYI: to make the initial text file with the string integers, what I did was:

Numbers = splittext[start:end]
Numbers = str(Numbers)
OutputFile.write(Numbers + "\n")  
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Mariıos
  • 273
  • 2
  • 5
  • Are the lines of the file `['1', '2', '3']` or `1, 2, 3`? – dawg Dec 24 '15 at 20:31
  • Doing `Numbers = str(Numbers)` was not a good idea, you should have just written the contents of the list then it would be a whole lot simpler to parse how you want, if you do want to keep a list format use json – Padraic Cunningham Dec 24 '15 at 20:45
  • lines of the file are ['1', '2', '3'] because I don't know how to remove all the extra stuff. Hence the Q. – Mariıos Dec 24 '15 at 20:52
  • @Mariıos, if you wrote the data correctly you would not have any issue parsing it, lots of example here http://stackoverflow.com/questions/899103/python-write-a-list-to-a-file – Padraic Cunningham Dec 24 '15 at 20:54
  • @Mariıos it looks like you have never accepted an answer for your questions. While there is no obligation to do so, please consider using the feature when you get an answer that solved your problem. This will make sure future readers of your questions know that an answer worked for you and will also give the answerer and you a small reputation boost. – timgeb Feb 26 '16 at 15:37

1 Answers1

3

You can use a list comprehension to loop over your file and then use ast.literal_eval to convert the string lists to list objects, and map to convert the string digits to int :

from ast import literal_eval
with open(file_name) as f:
   my_lists = [map(int,literal_eval(line.strip())) for line in f]
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
Mazdak
  • 105,000
  • 18
  • 159
  • 188