尝试在文本fi中写和读两个矩阵

2024-10-02 22:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: theintxt脚本foriswith矩阵
1条回答
网友
1楼 · 发布于 2024-10-02 22:26:19

您需要以^{}模式打开文件。你知道吗

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

如果矩阵不需要人类可读,我将使用^{}序列化它们,并避免重新创建它们。比如:

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

相关问题 更多 >