【问题标题】:How to read and write to lines in file with python如何使用python读取和写入文件中的行
【发布时间】:2020-08-19 08:59:30
【问题描述】:

如何打开一个文本文件,其中包含几个仅包含浮点数的列表,读取此文件中的每个列表,然后将新的浮点数附加到其中一个列表?

读取带有列表的文本文件:

[1.0, 2.0, 3.1] #list 1

[5.1, 2.9, 7.1] #list 2

[6.6, 7.9, 3.1] #list 3

打开列表 2 并追加新的浮点数; 5.5

结果:

[1.0, 2.0, 3.1] #list 1

[5.1, 2.9, 7.1, 5.5] #list 2

[6.6, 7.9, 3.1] #list 3

我尝试使用 json 模块和打开/写入功能,但我没有弄明白。

有什么好的建议吗? :)

【问题讨论】:

  • 文本文件实际上是什么样的?一行是否有括号和注释#list 编号?您想如何确定要附加的列表 - 仅列出 2?
  • 听起来像是关于如何操作类似 CSV 文件的作业。
  • 这能回答你的问题吗? How do I read and write CSV files with Python?

标签: python list file append readline


【解决方案1】:

您可以为此使用 json 文件。首先,您需要创建一个 json 文件来存储您的列表:

import json
with open('data.json', 'w') as f:
    json.dump(data, f)

data 包含您的列表。 data 可以是表单中浮动列表的嵌套列表

data = [[1, 2, 3], [3, 5, 2], [6, 7, 7]]

当您需要读取 json 文件时,您可以这样做:

with open("data.json", "r") as f:
    output = json.load(f)

现在output 有了您的列表,您可以遍历它们并附加您的新号码:

for nested_list in output:
    nested_list.append(number)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-17
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    相关资源
    最近更新 更多