Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从文件中读取数组_Python - Fatal编程技术网

Python 如何从文件中读取数组

Python 如何从文件中读取数组,python,Python,我在txt文件上写了一些数组,数组如下: [ 121.6 114.7 117.9 122.1 114.8 121.2 115.3 116.3 116. 121. 115.3 120.8 114.4 115.5 116.9 127.7 119.4 118.1 116.3 115.3 119.5 115.7 116.1 114.3 119. 116. 114.2 340.8 114.6 116.6 118.5 114.1 1

我在txt文件上写了一些数组,数组如下:

[ 121.6  114.7  117.9  122.1  114.8  121.2  115.3  116.3  116.   121.
  115.3  120.8  114.4  115.5  116.9  127.7  119.4  118.1  116.3  115.3
  119.5  115.7  116.1  114.3  119.   116.   114.2  340.8  114.6  116.6
  118.5  114.1  121.3  120.6  116.3]
with open('input.txt', 'r') as myfile:
    filearray = myfile.read()
还有一个这样的数组

[[122.54227 ]
 [123.13425 ]
 [122.04907 ]
 [122.696365]
 [123.1821  ]
 [121.818115]
 [123.11479 ]
 [121.908745]
 [122.193954]
 [121.94495 ]
 [122.76871 ]
 [121.7559  ]
 [122.98235 ]
 [121.78393 ]
 [122.06499 ]
 [122.05317 ]
 [123.91927 ]
 [122.679565]
 [123.07596 ]]

是否可以使用“读取文件”返回此数组表单?

首先,按如下方式读取并存储文件内容:

[ 121.6  114.7  117.9  122.1  114.8  121.2  115.3  116.3  116.   121.
  115.3  120.8  114.4  115.5  116.9  127.7  119.4  118.1  116.3  115.3
  119.5  115.7  116.1  114.3  119.   116.   114.2  340.8  114.6  116.6
  118.5  114.1  121.3  120.6  116.3]
with open('input.txt', 'r') as myfile:
    filearray = myfile.read()
如果filearray的内容被格式化为有效的python列表,例如[1、2、3、4]或[1]、[2]、[3]、[4]],则可以直接使用:

输出:

<class 'list'> [1, 2, 3, 4]
<class 'list'> [1, 2, 3, 4]
如果文件中的列表值不是逗号分隔的,则可以使用正则表达式将其格式化为有效的列表演示:

输出:

<class 'list'> [1, 2, 3, 4]
<class 'list'> [1, 2, 3, 4]

文本文件中的数组元素之间没有逗号?是的,这是可能的,到目前为止您尝试了什么?尝试一下,并向我们展示您的尝试!我尝试使用非逗号分隔形式,但我有一个错误:文件,第1行[117.71118.1194,121.6,114.7117.9,122.1114.81121.2,115.3^语法错误:无效语法请在帖子中包含文件内容,以便我可以相应地调整我的答案。现在它似乎有效,但为什么我有类似[1 2 3]的东西,是否存在问题?或者它仍然是一个1d数组它创建了一个元组,将列表作为第一个元素,因为re.sub在列表的末尾添加了一个逗号。我相应地编辑了我的代码。如果它仍然输出一个元组,您只需在代码的末尾添加iftypeoutputlist is tuple:outputlist=outputlist[0]即可获得列表。