【问题标题】:How to append text into a variable in a different python file?如何将文本附加到不同python文件中的变量中?
【发布时间】:2021-11-29 18:32:37
【问题描述】:

我正在尝试编写一个代码来获取用户输入的信息并将其永久添加到不同文件的变量中:

main.py:

text = "hello world"
f = open("Testfile.py", "a+")
f.write(text)

测试文件.py:

w = ["bob", "joe", "emily"]Hello World

我怎样才能让“Hello World”出现在 w 中,例如

w = ["bob", "joe", "emily", "Hello World"]

编辑:

如果 w 是一个库,例如 w = {"bob": 0, "joe": 0, "emily" : 0} 我想给它添加"Hello World" : 0

【问题讨论】:

  • 我不知道您的最终目标是什么,但这几乎可以肯定不是实现它的好方法。修改其他程序的程序可能会很快变得混乱。您遇到的任何错误都可能破坏您的代码并要求您重新开始。
  • 起点:ast 模块。 m = ast.parse(open('Testfile.py').read()),做你想做的然后ast.unparse(m)。使用ast.walk(尝试:list(ast.walk(m))
  • 关于您的编辑(和原始问题):只需使用 json 文件(用于编辑信息,否则给出任何答案),您不想写入实际的 python 文件以后会用到,没必要,而且很容易出问题
  • 这实在是太不合理了。
  • @juanpa.arrivillaga 我正在尝试制作一个不和谐的机器人来跟踪人们的观点,这就是为什么我需要一本字典来跟踪这些观点并“可编辑”

标签: python list variables append


【解决方案1】:

我强烈建议不要以编程方式修改 python 文件。通过将列表存储在文本文件中并让任何程序读取文本文件并构建列表,您可能能够完成相同的任务。您可以将其他文件格式用于更复杂的任务,但对于简单地将字符串放入列表中,此代码就足够了。某种完整的数据库最适合实际应用。

test.txt:

bob
joe
emily

main.py:

def read_file():
    f = open('test.txt', 'r')
    lines = f.readlines()
    lines = [line.strip() for line in lines] #removes the '\n' character at the end of each line
    print(lines)
    f.close()

def append_file(item):
    f = open('test.txt', 'a')
    f.write(item)
    f.write('\n')
    f.close()

read_file()
append_file("Hello World")
append_file("test")
read_file()

另外,您可以使用with 更简洁地管理文件对象。

def read_file():
    with open('test.txt', 'r') as f:
        lines = f.readlines()
        lines = [line.strip() for line in lines] #removes the '\n' character at the end of each line
        print(lines)


def append_file(item):
    with open('test.txt', 'a') as f:
        f.write(item)
        f.write('\n')

【讨论】:

  • 也可以代替lines = f.readlines() AND lines = [lines.strip() for line in line]lines = [line.strip() for line in f],它会少一行代码,可能更快,而且不需要两行f.write,你可以只需连接这些字符串
【解决方案2】:

真的有必要将数组的内容存储到 python 文件中吗? 例如,您可以将其存储到 yaml 文件中,然后使用 yaml 库将内容写入/读取该文件。

import yaml
import os

def load_yaml(filename):
  with open(filename, 'r') as fp:
    y = yaml.safe_load(fp)
    return y
def save_yaml(content, filename):
  if os.path.exists(filename):
    os.remove(filename)
  with open(filename, 'w') as fp:
    yaml.safe_dump(content, fp, default_flow_style=False)

w = ["bob", "joe", "emily"]
save_yaml(w, "data.yaml")
w.append("hello world")
save_yaml(w, "data.yaml")
content = load_yaml("data.yaml")
print(content)

【讨论】:

    猜你喜欢
    • 2014-03-17
    • 2021-12-15
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多