Python Split File Into List
Solution 1:
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
Solution 2:
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 inopen("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 = []
withopen('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']
Post a Comment for "Python Split File Into List"