Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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_Python 3.x - Fatal编程技术网

读取python文件的某些部分

读取python文件的某些部分,python,python-3.x,Python,Python 3.x,在python中,我想创建一个可以读取python文件一部分的代码。 例如,我要读取的文件 matrix1 =[[[1, 1, 1], [0, 0, 0], [1, 0, 0]], [[1, 0, 1], [0, 0, 0], [1, 0, 0]]] matrix2 = [[[1, 0, 1], [0, 0, 0], [1, 0, 0]], [[1, 0, 1], [1, 0, 1], [1, 0, 0]]] matrix3 = [[[1, 1, 1], [1, 1, 0],

在python中,我想创建一个可以读取python文件一部分的代码。 例如,我要读取的文件

matrix1 =[[[1, 1, 1], [0, 0, 0], [1, 0, 0]],
    [[1, 0, 1], [0, 0, 0], [1, 0, 0]]]

matrix2 = [[[1, 0, 1], [0, 0, 0], [1, 0, 0]],
    [[1, 0, 1], [1, 0, 1], [1, 0, 0]]]

matrix3 = [[[1, 1, 1], [1, 1, 0], [1, 0, 0]],
    [[1, 0, 1], [1, 0, 1], [1, 0, 0]]]

....
每组矩阵由一个空行分隔。 我只想读取矩阵1的内容,然后将其存储在变量中。然后我只想读取矩阵2的内容并将其存储在变量中。矩阵3也是这样

我的代码-

open('file.py')
matrix1 = read'file.py')
我的代码不起作用,因为现在它读取整个文件,而不仅仅是矩阵。
如何才能使我的输出是3个不同的嵌套矩阵,我可以将它们分别存储到不同的变量中。

使用存储在示例文件
file.py中的代码,您可以执行以下操作

exec(open('file.py').read())

print(matrix1)
请注意,如果用户可以访问file.py的内容,则这可能是不安全的


你可以这样做

从文件导入矩阵1
#或
从文件导入*作为数据
#然后像这样访问数据:
data.matrix1

如果文件已经是python文件,不要尝试手动打开文件,然后解析数据。这也适用于python文件中的其他内容,如类和函数。

我从未想过这一点。谢谢你,你真棒。我真的很愚蠢,因为我想得太多了。
[[[1, 1, 1], [0, 0, 0], [1, 0, 0]], [[1, 0, 1], [0, 0, 0], [1, 0, 0]]]