python - 有没有办法将项目永久添加到列表文件中?
问题描述
我正在制作一个 Python 脚本,它应该让我添加一个行会列表并按字母顺序对它们进行排序。因为我已经有了公会列表,所以我编写了一个 Python 文件,其中包含我已经拥有的名称列表。现在我需要将新项目附加到该列表中,因为该程序应该被多次使用,并且我需要在每次使用后将完整的列表与我输入的新项目一起保存。
这是我当前的代码:
from g_list import guilds # imports the guilds list from the g_list.py folder
def g_add():
f = open('Guilds_Sorted.txt','w')
f.write("\n".join(guilds))
f.close()
while True:
guild = input("What is the guild's name ? ") # can this input be saved back in the guilds list in g_list.py
f = open('Guilds_Sorted.txt', "a")
f.write('\n')
f.write(guild)
解决方案
尽管可以更新稍后要导入的 Python 文件,但这种情况极为罕见。
为什么不将初始公会存储在文本文件中,然后使用 Python 脚本向其中添加新公会?可以这样做:
PATH = 'Guilds_Sorted.txt'
def main():
# First read the already saved guilds from the file into memory:
with open(PATH, 'rt') as file:
guilds = file.read().splitlines()
# Now ask the user to add new guilds:
while True:
guild = input("What is the guild's name ? ")
if not guild:
break
guilds.append(guild)
# If you want, you can sort the list here, remove duplicates, etc.
# ...
# Write the new, complete list back to file:
with open(PATH, 'wt') as file:
file.write('\n'.join(guilds))
if __name__ == '__main__':
main()
请注意,我添加了退出条件。通过不输入名称(空字符串),程序退出。
推荐阅读
- can-bus - 如果消息是由交互式生成器块生成的,如何修改 CAPL 中的消息数据?
- javascript - 当您在 Popup 窗口中打开 Alert 窗口时,弹出窗口消失
- html - HTML - 为什么我的自定义 css 非动画光标没有显示?
- ruby-on-rails - Rails 5:创建付款时出现 AssociationTypeMismatch 错误
- javascript - 打字稿抱怨未分配 get 属性
- c++ - 为什么 C++ 中指向方法取消引用运算符的指针具有如此低的优先级?
- java - 在支持 bean 中使用 HashMaps
- excel - 使用 VBA 合并数据
- scala - 用火花处理“相关”线
- docker - 以非 root 用户身份在 Docker 容器中运行 Apache Ignite