0

I want to read an input file that has the format:

['1,2,3\r\n', '4,5,6']

I want them to be separated so it will look like

['1', '2', '3', '4', '5', '6']

My code looks like

def importFile(file):
with open(file) as f:
    content = f.readlines()
    print content
    for line in content:
        tempList = line.split(',')
    print tempList

Unfortunately, what I'm getting right now is

['4', '5', '6']

Where did I do wrong? Can anyone help me?

ThomasWest
  • 485
  • 1
  • 7
  • 21
  • 1
    You're overwriting the contents of `tempList` inside that `for` loop so you only have the contents from the last iteration. – mrogers Apr 12 '17 at 20:53
  • @mrogers I made some minor changes, but now I'm getting `[['1,2,3\r\n'], ['4,5,6']]`. What should I do next? – ThomasWest Apr 12 '17 at 20:59

1 Answers1

1

To reiterate my comment: the issue is that you're overwriting tempList at each iteration of the for loop (each line of your file). Below is one way you could solve the issue. I borrowed the regex to pull digits out of your lines to get rid of the \r\n from Python: Extract numbers from a string. The core of this solution is that second for loop that iterates over the contents of each line.

import re

def importFile(file):
    with open(file) as f:
        content = f.readlines()
        print content
        result = []
        for line in content:
            tempList = line.split(',')
            for x in tempList:
                result.append(re.findall(r'\d+', x)[0])
        print result
Community
  • 1
  • 1
mrogers
  • 1,187
  • 2
  • 15
  • 22