gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:18:51 25 4
gpt4 key购买 nike

我有一个包含大量代码和列表的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com