3

I'm having trouble with the function below. It seems to split the file fine but then only returns it as one element

Function:

def splitRoute():
  route = []
  for line in open("route.txt","r").readlines():
    line = line.replace("\r","")
    line = line.replace("\n","")
    line = string.split(line, '>')
    route.append(line) 
  return route

Output:

[['B', 'F']]

route.txt contents:

B>F

Is it only returning one element because there is only one line in the file? I have another function that splits another file into a 7x7 list that works fine but is that only reaching all seven elements across because it has 7 lines?

1
  • Well, what else were you expecting? Commented Feb 20, 2012 at 2:41

2 Answers 2

3

Why are you replacing newlines? Just split the string:

def splitRoute():
  route = []

  for line in open('route.txt', 'r'):
    route.append(line.strip().split('>')) 

  return route
Sign up to request clarification or add additional context in comments.

2 Comments

@Schmooo, it also creates a new copy of the list every time + is used. I'd suggest using extend instead of append; then you don't have to use sum at all.
I just realised this doesn't work if the route.txt is multiline. It takes all the lines in the file and adds it to one line in the list. I need it to split it into a 2d list so 2x3 for a three line file.
1

split creates a list. Then you append that list to another (empty) list. So the result is that you get a list inside a list. If you had more lines, you'd get a longer list of lists. Here's a quick breakdown of the code:

def splitRoute():
  route = []

You create an empty list...

  for line in open("route.txt","r").readlines():
    line = line.replace("\r","")
    line = line.replace("\n","")

For every line, you replace \r and \n characters with empty strings. Note that you could do this more easily using line.strip() ('apple\n\r'.strip() -> 'apple'). Also, you should save the file to a filename so you can close it later. Finally, you don't need to use readlines here -- just iterate over the file directly.

    line = string.split(line, '>')

Now you take the string that line refers to, split it into a list, and assign the list to line. Now line looks like this: ['B', 'F'].

    route.append(line) 
    return route

Now you've appended line to route, and route looks like this: [['B', 'F']].

If your goal is to create a single list, use extend instead of append.

def splitRoute():
  route = []
  f = open('route.txt', 'r')
  for line in f:
    route.extend(line.strip().split('>'))
  f.close()
  return route

Or, using with, and adopting a more readable indentation level:

def splitRoute():
    route = []
    with open('route.txt', 'r') as f:
        for line in f:
            route.extend(line.strip().split('>'))
    return route

Output for a file with two lines ('B>F\nF>X\n'):

>>> splitRoute()
['B', 'F', 'F', 'X']

2 Comments

Do I need the list within a list to make it a 2D array or is there a way that this can be done with just one list?
If you want a 2D array, use append instead of extend. The most straightforward way to create a 2D array in Python is indeed to create a list of lists. You could also use tuples to index a dict; d = {}; d[0, 0] = 1; d[0, 1] = 0; d[1, 0] = 1; d[1, 1] = 0 and so on. But this is somewhat slower than a list of lists in most cases.

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.