Numbers separated by spaces in txt file into python list
<p>I am trying to convert a txt file containing lines of numbers separated by spaces into numbers separated by commas in lists, where each line is a new list of these numbers using Python 3.</p>

<p>E.g. txt file contains </p>

<blockquote>
  <p>1  2  3  4  5</p>
  
  <p>6  7  8  9  10</p>
</blockquote>

<p>and I want this in python:</p>

<pre><code>[1,2,3,4,5]

[6,7,8,9,10]
</code></pre>

<p>I can't seem to find a good solution, I used numpy and obtained the list of lists but not comma separated, e.g.:
<code>[[1  2  3  4  5],[6  7  8  9 10]]</code></p>

<p>Here is the example code I've used that doesn't quite work:</p>

<pre><code>import numpy as np

mymatrix = np.loadtxt('file')
</code></pre>

<p>Grateful for any input! (ps I'm a beginner but want to use the lists in a programme I am developing)</p>

<p>Following uses plain Python 3 (without NumPy)</p>

<pre><code># open file
with open('file.txt') as fp:
    # 1. iterate over file line-by-line
    # 2. strip line of newline symbols
    # 3. split line by spaces into list (of number strings)
    # 4. convert number substrings to int values
    # 5. convert map object to list
    data = [list(map(int, line.strip().split(' '))) for line in fp]
</code></pre>

<p>This provides the result you're looking for:</p>

<pre><code>&gt;&gt;&gt; with open('data.txt') as fp:
...     data = [list(map(int, line.strip().split(' '))) for line in fp]
... 
&gt;&gt;&gt; print(data)
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
</code></pre>

python