【问题标题】:How to read array of integers from file and store it in array如何从文件中读取整数数组并将其存储在数组中
【发布时间】:2023-01-19 18:16:43
【问题描述】:

我将数组存储到文件中:

file = open("file1.txt", "w+")
 
    # Saving the 2D array in a text file
    content = array2d
    file.write(str(content))
    file.close()

现在我必须在文件中使用看起来像这样的数组(这只是缩短):

[[[ 253  122]
  [ 253  121]
  [ 253  121]
  ...
  [1027  119]
  [1027  120]
  [1028  120]]

 [[ 252  122]
  [ 253  122]
  [ 253  122]
  ...
  
  [1067  573]
  [1067  573]
  [1067  573]]]

我必须打开这个文件并将数组存储在新文件中,以便在保存之前访问所有整数元素。

我试过:

text_file = open("file1.txt", "r")
data = []
data = text_file.read()

text_file.close()

print(data[0])

作为第一个元素数据 [0] 给我 [ 它应该是 253。

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

它给你“[”因为它是一个纯粹的文本文件,因此字符串数组的第一个字符就是“[”。 我建议使用 numpy.save 来保存数组:https://numpy.org/doc/stable/reference/generated/numpy.save.html 和 numpy.load 用于加载数组:https://numpy.org/doc/stable/reference/generated/numpy.load.html

简单地说, numpy.save('name_of_file_to_save', array_to_save) 并加载:numpy.load('name_of_file_to_save')

【讨论】:

    【解决方案2】:

    使用泡菜的简单方法

    import pickle
    
    file =  open("file1.txt", "wb") #file
    
    content = [[[ 253 , 122],[ 253 , 121],[1067  ,573]]]
    pickle.dump(content,  file) #saving
    file.close()
    
    file =  open("file1.txt", "rb") #file
    data= pickle.load(file) #loadinga file
    file.close()
    
    print(data[0]) #e.x
    

    【讨论】:

    • numpy 已经有这方面的功能。问题中显示的输出很可能是由 numpy 数组产生的。
    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 2015-01-22
    • 2012-11-22
    • 1970-01-01
    • 2020-02-09
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多