试图在文本文件中写入和读取两个矩阵

时间:2014-03-27 11:42:15

标签: python file-io matrix

从Python脚本中,我需要在文本文件中编写两个float矩阵,在第二个Python脚本中我想再次读取文本文件。所以我试着用这种方式:

#ElR is the first matrix and ShR is the second matrix
with open("house.txt", "w") as fE:
    fE.writelines(','.join(str(j) for j in i) + '\n' for i in ElR)

with open("house.txt", "w") as fS:
    fS.writelines(','.join(str(j) for j in i) + '\n' for i in ShR)

但是,执行此操作时,只在文本文件中写入ShR的值而不是ElR的值。它有什么问题? 而且,是否可以通过任何方式读取文本文件并将两个矩阵保存在其他矩阵中?所需的脚本看起来像这样(我猜):

r_file = open("house.txt", "r")
new_ElR = r_file.readline()
new_ShR = r_file.readline()
r_file.close()

1 个答案:

答案 0 :(得分:3)

您需要使用append模式打开文件。

#ElR is the first matrix and ShR is the second matrix
with open("house.txt", "w") as fE:
    fE.writelines(','.join(str(j) for j in i) + '\n' for i in ElR)

with open("house.txt", "a") as fS: # <-- notice the a
    fS.writelines(','.join(str(j) for j in i) + '\n' for i in ShR)

现在你要在第二个with - 块中覆盖该文件。使用上述解决方案,您将覆盖第一个文件中的现有文件,并在第二个文件中附加到该文件。

或者如本回答的评论中所述,您可以一次性写出来。

#ElR is the first matrix and ShR is the second matrix
with open("house.txt", "w") as fE:
    fE.writelines(','.join(str(j) for j in i) + '\n' for i in ElR)
    fE.writelines(','.join(str(j) for j in i) + '\n' for i in ShR)

您可以通过连接列表来缩短它。

with open("house.txt", "w") as fE:
    fE.writelines(','.join(str(j) for j in i) + "\n" for i in ElR + ShR)

如果矩阵不需要是人类可读的,我会使用pickle对它们进行序列化,并避免重新创建它们。类似的东西:

>>> import pickle
>>> with open("my_matrices.pkl", "wb") as f:
...    pickle.dump(my_matrix_object, f)
...

当你需要它们时......

>>> with open("my_matrices.pkl", "rb") as f:
...    matrix = pickle.load(f)
...