【问题标题】:Write a basic array to a txt file? [closed]将基本数组写入txt文件? [关闭]
【发布时间】:2017-02-01 22:40:57
【问题描述】:

我一直在努力完成将 python 数组写入 txt 文件的简单任务。

假设我有一个数组

a = ["hello", "stack overflow"]

我需要一种获取文本文件 (array.txt) 来保存这个数组的方法——我不关心它以什么格式保存:

"hello" "stack overflow"

也许将其转换为字符串然后写入array.txt 会更容易。在这种情况下我该怎么写:

a = "hello stack overflow"

到array.txt。

【问题讨论】:

  • 你有什么问题?
  • 您尚未列出您尝试过的内容。如果你没有发现你的误解,那么没有答案可以为你正确地解决它。
  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 on topichow to ask 在这里申请。 StackOverflow 不是编码或教程服务。
  • 人们回答:请不要鼓励发帖者使用 Stack Overflow 代替基础研究。

标签: python arrays string writing


【解决方案1】:

使用json.dump,您可以轻松地将python 列表或字典保存到文件中,然后使用json.load 重新打开它。

import json
a = ["hello", "world"]
with open("output.txt", "w") as outfile:
    json.dump(a, outfile)

再次从文件加载数组:

import json
with open("output.txt", "r") as infile:
    a = json.load(infile)

【讨论】:

  • 我得到 TypeError: array([ 0., 0., 0., ..., 2., 2., 2.]) is not JSON serializable
【解决方案2】:

或者更简单,您可以将列表与以下内容合并:''.join(array)

这需要很少的迭代,使用内置函数通常意味着更好的性能,内置函数通常是用 C 编写的。它也不需要模块。

这是一个例子

a = ["hello","stack overflow"]

a_merged = ' '.join(a)
with open("array.txt",'w') as f:
    f.write(a_merged)

【讨论】:

  • 已编辑。谢谢叶子。
  • 谢谢 :) 我会试试这个
  • 感谢您的考虑 :) 帮了我很多忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
相关资源
最近更新 更多