Hi everybody,
Im pretty new (or u can say that completely new) to python and i try to learn from the very basic. I try to create grid data structure from array. Here i have some code, would you mind to look at it and give me an instruction:

import math

class Grid(object):
def __init__(self, width = 10, height = 10):
self.width = width
self.height = height
self.size = size
self.grid = []
cell_value = 0

.....

then i got stucked, i would like to print out this array and then save it into text file! i look some place and it gave me this

import numpy as np
x = np.arange(20).reshape((4,5))
np.savetxt('test.txt', x)

but i dont know how to print it then save it into text file
if i have value with coordinate (x,y) later, can i change it in text file? and how?

thank you very much, it will be helpful
hancook

If you want to change the file you read the values, do changes in memory and save to file again.

import math

class Grid(list):
    def __init__(self, cell_value=0, width = 10, height = 10):
       list.__init__(self, [[cell_value for _ in range(width)]
                        for _ in range(height)])
       self.cell_value = cell_value
       
    def save(self, fname):
        with open(fname, 'w') as out:
            for row in self:
                out.write(', '.join(str(column)for column in row))
                out.write('\n')

    def __str__(self):
        res = '[\n'
        for row in self:
            res += '     ' + str(row) + ',\n'
        return res[:-2] +'\n]'

    __repr__ = __str__

grid = Grid()
print grid
grid [7][8] = 4
print grid
grid.save('grid.txt')
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.