简体   繁体   中英

Write 2d array into a text file in python

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM