Reputation: 1071
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?
Upvotes: 3
Views: 17396
Reputation: 298048
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
Upvotes: 3
Reputation: 150947
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']
Upvotes: 1