Reputation: 35
The following code fills a 2d array (grid) with random numbers(0 or 1):
def create_initial_grid(rows, cols):
grid = []
for row in range(rows):
grid_rows = []
for col in range(cols):
if random.randint(0, 7) == 0:
grid_rows += [1]
else:
grid_rows += [0]
grid += [grid_rows]
return grid
I want to fill the grid from a text file that looks like this:
7
0,0,0,0,0,0,0
0,0,1,0,1,0,0
0,0,1,1,1,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
Upvotes: 2
Views: 979
Reputation: 2500
Other option is to use numpy.loadtxt to read .txt
(since you are use the array
and matrix
format):
data = np.loadtxt("text.txt", delimiter=",",dtype=int , skiprows=1)
print(data)
Out:
[[0 0 0 0 0 0 0] [0 0 1 0 1 0 0] [0 0 1 1 1 0 0] [0 0 0 0 0 0 0] [0 0 0 0 0 0 0] [0 0 0 0 0 0 0] [0 0 0 0 0 0 0]]
Note:
skiprows=1
# parameter for skipping the first line when reading from the file.
dtype=int
parameter for reading in theint
format (default isfloat
)
Upvotes: 1
Reputation: 166
filesname = "t.txt"
with open(filesname) as f:
lines = f.read().split()
n = lines[0]
data_lines = lines[1:]
data = [map(int, row.split(",")) for row in data_lines]
print(data)
Hope this helps!
Upvotes: 0
Reputation: 476594
You can read the file, with:
with open('myfile.txt') as f:
next(f) # skip the first line
data = [list(map(int, line.strip().split(','))) for line in f]
Here next(..)
will move the cursor to the next line, since the first here contains a 7
.
If there is data after the lines, we might want to prevent reading that, and use:
from itertools import islice
with open('myfile.txt') as f:
n = int(next(f)) # skip the first line
data = [list(map(int, line.strip().split(','))) for line in islice(f, n)]
For both file fragments here, the result is:
>>> data
[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]
Upvotes: 0