简体   繁体   English

python3:如何将 append 列表转换为外部 python 文件中的空列表?

[英]python3: How to append a list to an empty list in an external python file?

There is a list-有一个列表-

#main_file.py
f = ['foo','bar']

that I want to append to an empty list in an external python file.我想 append 到外部 python 文件中的空列表。
The external file already has an empty list g外部文件已经有一个空列表g

#external_file.py
g = []

So far I have tried this in the main file-到目前为止,我已经在主文件中尝试过这个 -

#main_file.py
h = open("external_file.py", "a")
g.append(f)
h.close()

But it didn't work但它没有用

You can do你可以做

import re

with open("external_file.py", "r+") as h:
    stmt = h.read()
    exec(stmt)
    val_name = stmt[:stmt.find("=")].strip()
    eval(val_name).extend(f)
    h.seek(0)
    h.write(re.sub("\[.*\]", str(eval(val_name)), stmt))

Because you are reading for a file then the statement "g = []" is text so you need to exec() it the it will be converted to g = [] .因为您正在读取一个文件,所以语句"g = []"是文本,所以您需要exec()它会将其转换为g = []
After there is a need to extend the f list in to the g and to remove the original "g = []" with the new extended list and write it back to the file.在需要将 f 列表扩展到 g 并用新的扩展列表删除原来的"g = []"并将其写回文件之后。

You can try by importing the first external_file.py and then append the list f from the main_file.py您可以尝试导入第一个external_file.py ,然后导入 append 来自main_file.py的列表f

#main_file.py

import external_file as externalFile
f = ['foo','bar']
externalFile.g.append(f)
#print(externalFile.g)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM