gpt4 book ai didi

python - 我怎样才能告诉 python 编辑另一个 python 文件?

转载 作者:行者123 更新时间:2023-11-28 22:46:16 24 4
gpt4 key购买 nike

现在,我有 file.py 并将单词“Hello”打印到 text.txt 中。

f = open("文本.txt")
f.write("你好")
f.close()

我想做同样的事情,但我想将单词“Hello”打印到 Python 文件中。假设我想做这样的事情:

f = open("list.py")
f.write("a = 1")
f.关闭

当我打开文件 list.py 时,它会有一个值为 1 的变量 a 吗?我该怎么做呢?

最佳答案

如果你想在文件末尾追加一个新行

with open("file.py", "a") as f:
f.write("\na = 1")

如果你想在文件的开头写一行尝试创建一个新的

with open("file.py") as f:
lines = f.readlines()

with open("file.py", "w") as f:
lines.insert(0, "a = 1")
f.write("\n".join(lines))

关于python - 我怎样才能告诉 python 编辑另一个 python 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27664830/

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