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()
2
  • What do you mean by single line? Row followed by other rows without and formatting i.e a single number line? Commented May 26, 2022 at 3:31
  • @melarCoder Single line means like this: [[0,1, 0], [2, 0, 0], [3, 0, 2], [2, 1, 1], [0, 0, 2]] But in the file, it is in a 2d arrayform Commented May 26, 2022 at 3:43

1 Answer 1

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]]
Sign up to request clarification or add additional context in comments.

2 Comments

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()

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.