繁体   English   中英

如何在其他 python 文件中的 append 特定列表并保存

[英]How to append particular list in other python file and save it

我需要更改保存在其他 python 文件中的列表中的项目

文件 A.py

items = ['A','B','C']

文件 B.py

import A

A.items.append('D')

它可以工作,但是当我重新启动脚本时,它会切换到以前的版本。

当应用程序退出时,该应用程序使用的 memory 将被释放。 这就是我们需要文件的原因,我们可以将数据写入文件。 此外,您的代码在运行时执行的操作不会影响任何源代码。

如果您的items将是一个字符串列表,您可以使用这样的轻量级解决方案:

#a.py
import os, ast

items = ['A','B','C']

file = "data.txt" # the file we will write our data in

if os.path.exists(file): # if our file exists
    with open(file, "r") as f: # open it in 'r'ead mode
        items = ast.literal_eval(f.read()) # read it and evalute
else: # if our file doesn't exists
    with open(file, "w") as f: # open it in 'w'rite mode
        f.write(str(items)) # write str(items) into file
#b.py
import a

a.items.append("D")

with open("data.txt", "w") as f: # open our file in 'w'rite mode
    f.write(str(a.items)) # save a.items

作为一般解决方案,您还可以使用picklejson模块来保存列表或其他对象。


文件:

ast.literal_eval ,打开, os.path

您需要将数据存储在文件中才能保存。

在此脚本中,我在文件 A 中有项目列表,文件 B 将“D”添加到列表中,然后将其添加到 txt 文件中。

您可以在运行文件 B 后打印文件 A 中的 txt 文件以查看新项目列表。 新列表保存为 new_items

如果您多次运行文件 B,它将多次添加列表。

档案一:

items = ['A','B','C']

#prints out the txt file
with open("items.txt","r") as f:
    new_items = f.read()
    new_items = new_items.split()
    print(new_items)
    f.close()

文件 B:

import A

#Adds 'D' to the items list and stores it as a new variable
A.items.append('D')
items = A.items

#Writes the data to a txt file
with open('items.txt', 'a') as f:
    f.write(str(items))

暂无
暂无

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

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