1

I need to write a 2D randomized array with a size of [5][3] into a text file. How can I write it in a single line in the text file? The output that I got from the file is in matrix form, not in a single line. The reason why I want to write it as a single line is that I want to write another array called max for the second line in the text file (I also don't know how to code this).

import numpy as np
from numpy import random

process = 5
resources = 3
allocation = [[0 for i in range(resources)]for i in range(process)]

def writeFile(allocation, process, resources):
file = open("test.txt", 'w')
for i in range(process):
    for j in range(resources):
        allocation = random.randint(10, size=(5, 3))
file.write(str(allocation))
file.close()

return

if __name__ == '__main__':
writeFile(allocation, process, resources)

file = open("test.txt", 'r')
allocation = np.array(file.readlines())
print(*allocation)
file.close()
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40

1 Answers1

2
allocation = []
def writeFile(allocation, process, resources):
    file = open("test.txt", 'w')
    for i in range(process):
        temp = list(random.randint(10, size=(resources)))
        allocation.append(temp)
    file.write(str(allocation))
    file.close()
    return

Your code was generating a random 5x3 matrix for each iteration. To write a single line to the file, I appended each row as a list and casted it as a string in the end. The output for the above code is:

[[0, 5, 9], [5, 4, 4], [7, 3, 9], [4, 6, 4], [9, 5, 8]]
melarKode
  • 87
  • 1
  • 10
  • Oh yes! This is what I'm looking for. Can I ask one more question? How to store it in a 2d array again when I read it and want to print the length of the array? Below is the code that I have tried but this error occurred "TypeError: len() of unsized object" file = open("test.txt", 'r') y = np.array(file.readline()) print(y) print(len(y)) file.close() – someonewhoisstilllearning May 26 '22 at 04:09
  • Refer to this answer for [converting a string representation of a list to a list](https://stackoverflow.com/a/1894296/13227971). – melarKode May 26 '22 at 04:12