【问题标题】:Python program for writing length of list to file用于将列表长度写入文件的 Python 程序
【发布时间】:2020-05-13 17:42:05
【问题描述】:

我有一个文件list.txt,其中仅包含一个列表,例如

[asd,ask,asp,asq]

列表可能很长。我想创建一个python程序len.py,它读取list.txt并将内列表的长度写入文件num.txt。类似于以下内容:

fin = open("list.txt", "rt")
fout = open("num.txt", "wt")

for list in fin:
    fout.write(len(list))

fin.close()
fout.close()

但是这不起作用。有人能指出需要改变什么吗?非常感谢。

【问题讨论】:

  • 欢迎来到 Stack Overflow。你读过documentation for the open() function吗? open() 返回一个 File 对象并且不能自己解释文件的内容。
  • 这能回答你的问题吗? Convert string representation of list to list
  • @esqew 谢谢。我认为这不能回答它,但是我对 python 一点也不熟悉。我正在使用的输入文件来自另一个应用程序,只是我需要一种读取它的长度的方法。我会看看引用的文档。
  • 您应该考虑将 list.txt 设置为 json 文件,以便文件中的文本为 ["'asd", "ask", "asp", "asq"],然后您可以将其加载为实际的 python 列表并使用 len() 查看它的长度功能。另外,我不会将您的模块命名为len.py,因为len 是一个内置的python 函数

标签: python


【解决方案1】:

用途:

with open("list.txt") as f1, open("num.txt", "w") as f2:
    for line in f1:
        line = line.strip('\n[]')
        f2.write(str(len(line.split(','))) + '\n')

【讨论】:

    【解决方案2】:
    with open("list.txt") as fin, open("num.txt", "w") as fout:
        input_data = fin.readline()
        # check if there was any info read from input file
        if input_data:
            # split string into list on comma character
            strs = input_data.replace('[','').split('],')
            lists = [map(int, s.replace(']','').split(',')) for s in strs]
            print(len(lists))
            fout.write(str(len(lists)))
    

    我更新了代码以使用另一个答案中的 with 语句。我还使用了这个答案 (How can I convert this string to list of lists?) 中的一些代码来(更多?)正确计算嵌套列表。

    【讨论】:

    • 非常感谢。运行此命令时,我在第 10 行遇到错误:fout.write(len(output_list)) TypeError: expected a character buffer object
    • 我更新了代码以避免这个问题。 len() 函数返回一个整数,但 write() 需要一个字符串。它现在应该可以正常运行了。
    【解决方案3】:

    当 python 尝试使用默认方法读取文件时,它通常将该文件的内容视为字符串。因此,首要责任是将转换字符串内容键入适当的内容类型,因为您不能使用默认类型转换方法。

    您可以使用名为 ast 的特殊包对数据进行类型转换。

    import ast
    
    fin = open("list.txt", "r")
    fout = open("num.txt", "w")
    
    for list in fin.readlines():
        fout.write(len(ast.literal_eval(list)))
    
    fin.close()
    fout.close()
    

    【讨论】:

      猜你喜欢
      • 2018-01-05
      • 1970-01-01
      • 2013-10-30
      • 2015-09-09
      • 2020-08-19
      • 2015-05-29
      • 2021-09-02
      • 2010-10-28
      相关资源
      最近更新 更多