Reputation: 121
I have to read from file into a 2D list. The file looks like:
Jack 32
Perry 12
Tim 14
etc.
When I print the list it looks like:
['Jack 32', 'Perry 12', 'Tim 14']
But I need it to look like:
['Jack', '32', 'Perry', '12', 'Tim', '14']
So far my code looks like this:
with open('filelocation', 'r') as f:
content = f.readlines()
content = [x.strip('\n') for x in content]
print(content)
Upvotes: 1
Views: 848
Reputation: 28656
Can't you just split the whole file on whitespace?
>>> with open('filelocation') as f:
print(f.read().split())
['Jack', '32', 'Perry', '12', 'Tim', '14']
No point creating structure only to flatten it away.
Upvotes: 3
Reputation: 6835
Why not stream the file into a string with spaces between the new lines, then split by the space?
All you want to do is split by space anyway.
I know this isn't the "sexiest" answer, but probably the most straight forward for your use case.
Upvotes: 0
Reputation: 19771
Try like this:
my_list = []
with open('your_file') as f:
for x in f:
my_list += x.strip().split()
Upvotes: 1
Reputation: 180550
You can chain the elements with itertools.chain after splitting each line:
from itertools import chain
with open('filepath') as f:
content = list(chain.from_iterable(x.split() for x in f))
print(content)
['Jack', '32', 'Perry', '12', 'Tim', '14']
You don't need to call .readlines
, you can iterate over the file object f
. line.strip("\n")
just strips the newlines, you don't actually split. If you call split on each line you will end up with a list of lists like [['Jack', '32'], ['Perry', '12'], ['Tim', '14']]
, chain.from_iterable
chains the elements from each sublist into a single list.
.readlines
reads all the lines into memory at once which for a small file won't matter but if you have large files or restricted memory you should avoid calling .read
or .readlines
.
Upvotes: 0
Reputation: 6606
You should just be able to read as a string and split on whitespace.
with open('filelocation') as f:
split_up = f.read().split()
Upvotes: 1
Reputation: 28313
Split the string for each element in ['Jack 32', 'Perry 12', 'Tim 14']
using space as a separator (default).
Iterate through the resulting list to flatten it out.
mylist = ['Jack 32', 'Perry 12', 'Tim 14']
my_new_list = []
for l in mylist:
my_new_list.extend(l.split())
Or, you could use a generator
Upvotes: 1
Reputation: 5347
There might be a simple method than this
In [46]: a=['Jack 32', 'Perry 12', 'Tim 14']
In [47]: b=[i.split() for i in a ]
In [49]: b
Out[49]: [['Jack', '32'], ['Perry', '12'], ['Tim', '14']]
In [50]: [item for sublist in b for item in sublist]
Out[50]: ['Jack', '32', 'Perry', '12', 'Tim', '14']
Upvotes: 0
Reputation: 73
I think if you took the contents of the list you get back and split it on white space that will give you what you're looking for.
https://docs.python.org/2/library/stdtypes.html#str.split
Upvotes: 0