使用 Python,我需要将二维矩阵写入文件中,以便以下命令可以轻松读取它:
with open("matrix.txt") as textFile:
matrix = [line.split() for line in textFile]
Run Code Online (Sandbox Code Playgroud)
我已经尝试过了file.write(str(matrix)),它写得很好,但它并没有按照我需要的方式来稍后提取数据。
我所拥有的是以下内容:
[[1, 2, 3,][4, 5, 6][7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)
我希望文件具有什么内容;
1 2 3
4 5 6
7 8 9
Run Code Online (Sandbox Code Playgroud)
有任何想法吗???
您可以将矩阵的各个行转换为以空格分隔的字符串,并将其写入文本文件。
matrix = [[1, 2, 3,],[4, 5, 6],[7, 8, 9]]
with open('matrix.txt', 'w') as testfile:
for row in matrix:
testfile.write(' '.join([str(a) for a in row]) + '\n')
Run Code Online (Sandbox Code Playgroud)