2

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
2
  • To read a row, you could simply do row.split(','). Commented Oct 27, 2018 at 18:08
  • I removed your image and wrote it as text. I did this for you, because you are new, but you should do that yourself in the future. See Why not upload images of code on SO when asking a question Commented Oct 27, 2018 at 18:11

3 Answers 3

1

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 the int format (default is float)

Sign up to request clarification or add additional context in comments.

Comments

0

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]]

Comments

0
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!

1 Comment

This won't work in Python 3.x where map is a lazy iterator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.