当我从另一个文件导入数组时,我是只从中获取数据还是需要 "build" 数组以及原始文件的构建方式?
When I import an array from another file, do I take just the data from it or need to "build" the array with how the original file build it?
抱歉,如果问题表述不当,将在必要时重新表述。
我有一个包含数组的文件,我从在线 json 数据库中填充了数据,我将这个数组导入另一个文件以使用它的数据。
#file1
response = urlopen(url1)
a=[]
data = json.loads(response.read())
for i in range(len(data)):
a.append(data[i]['name'])
i+=1
#file2
from file1 import a
'''do something with "a"'''
导入数组是否意味着我每次在file2中调用它时都在填充数组?
如果是这种情况,我该怎么做才能只保留数组中的数据而不是每次调用它时都“构建”它?
从模块部分的 Python 文档 - link - 您可以阅读:
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it
这意味着导入模块的行为与 运行 作为常规 Python 脚本的行为相同,除非您使用此引文后提到的 __name__
。
还有,仔细想想,你是打开东西,从里面读取,然后做一些操作。您如何确定您现在正在阅读的内容与您第一次阅读的内容相同?
如果您将 a 保存到文件,然后读取 a -- 您将不需要重建 a -- 您可以直接打开它。例如,这是打开文本文件并从文件中获取文本的一种方法:
# set a variable to be the open file
OpenFile = open(file_path, "r")
# set a variable to be everything read from the file, then you can act on that variable
file_guts = OpenFile.read()
抱歉,如果问题表述不当,将在必要时重新表述。
我有一个包含数组的文件,我从在线 json 数据库中填充了数据,我将这个数组导入另一个文件以使用它的数据。
#file1
response = urlopen(url1)
a=[]
data = json.loads(response.read())
for i in range(len(data)):
a.append(data[i]['name'])
i+=1
#file2
from file1 import a
'''do something with "a"'''
导入数组是否意味着我每次在file2中调用它时都在填充数组? 如果是这种情况,我该怎么做才能只保留数组中的数据而不是每次调用它时都“构建”它?
从模块部分的 Python 文档 - link - 您可以阅读:
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it
这意味着导入模块的行为与 运行 作为常规 Python 脚本的行为相同,除非您使用此引文后提到的 __name__
。
还有,仔细想想,你是打开东西,从里面读取,然后做一些操作。您如何确定您现在正在阅读的内容与您第一次阅读的内容相同?
如果您将 a 保存到文件,然后读取 a -- 您将不需要重建 a -- 您可以直接打开它。例如,这是打开文本文件并从文件中获取文本的一种方法:
# set a variable to be the open file
OpenFile = open(file_path, "r")
# set a variable to be everything read from the file, then you can act on that variable
file_guts = OpenFile.read()