Python 2.7 从另一个 python 文件加载和编辑列表

标签 python python-2.7

我有一个包含大量代码和列表的 python 文件。我需要在特定列表中添加列。

我的问题是 - 如何从 .py 文件加载特定列表?并且,如何将元素添加到特定列表中?

在我的代码中:

import os, datetime, json

login1 = os.environ["login"].split('\')[1].strip()
login = login1.split('.')[0].strip()
USERID = str(os.environ['USERID'])
header = login + USERID + '.json'

with open("d:\\python\\monitor.py", "r") as infile:

data = infile.readlines()

#here I need to load a "dev_personal_files" list and append additional element

monitor.py文件的内容

#some python code
dev_personal_files = [
'Yura.json',
'Sasha.json'
]       
staging_files = [
#'ple.json',
'retailReleaseServer.json', 
'topaz.json',
'ple2.json',
#'klub.json',
'gaabtMX.json'
]
staging_files2 = [
'retailDemo.json',
'resort.json',
'jhnkljkl.json',
'hbjk,nm,.json',
'bnbnj,jnk,.json'
]
#some python code

我想添加到“dev_personal_files”列表中的内容(monitor.py 文件中的列表):

dev_personal_files = [
'NEWRECORD.json',
'Yura.json',
'Sasha.json'
]   

最佳答案

.py 文件获取列表(或任何对象)是通过导入文件来完成的:

import mypyfile # <- leave off the .py 

importedlist =  mypyfile.dev_personal_files

或者您可以只导入对象本身:

from mypyfile import dev_personal_files

dev_personal_files.extend(my_list_of_extra_items)

但是,在结束 Python session 后,对列表的更改将会丢失。

如果要永久存储对列表的更改,请以 json 等格式保存,而不是保存在 py 文件中。

import json

# Read data from the file
with open('myfile.json') as f:
    my_list = json.load(f)

# Add an item to your list
my_list.append('foo')

# Save data to the file
with open('myfile.json', 'w') as f:
    json.dump(my_list)

关于Python 2.7 从另一个 python 文件加载和编辑列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54039894/

相关文章:

python-2.7 - 如何利用最小读/写单元执行 AWS DynamoDB 备份和还原操作?

python - 压缩到python中的特定目录

python-2.7 - festival tts的语速可以改吗?

python - 将有序字典修剪到最后 x 项

python - 添加第二个 x_axis 覆盖标题

python - 如何在不覆盖数据的情况下写入现有的 excel 文件(使用 pandas)?

python - 如何避免从元类派生的动态生成的类最终不会成为同一个类?

python - 缩放图片的一部分

python - Django:如何管理开发和生产设置?

Python 自定义异常处理