-1

I have a file list.txt that contains a single list only e.g.

[asd,ask,asp,asq]

The list might be a very long one. I want to create a python program len.py that reads list.txt and writes the length of the within list to the file num.txt. Something like the following:

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

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

fin.close()
fout.close()

However this does not work. Can someone point out what needs to be changed? Many thanks.

RedOrange
  • 103
  • 1
  • Welcome to Stack Overflow. Have you read through the [documentation for the `open()` function](https://docs.python.org/3/library/functions.html#open)? `open()` returns a `File` object and isn't capable of *interpreting* the contents of the file on its own. – esqew May 13 '20 at 17:45
  • Does this answer your question? [Convert string representation of list to list](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) – esqew May 13 '20 at 17:46
  • @esqew Thanks. I don't think that answers it, but then I'm not familiar at all with python. The input file I'm using comes from another application and just I need a way of reading its length. I will have a look at the documentation referenced. – RedOrange May 13 '20 at 17:55
  • you should consider making list.txt a json file so your text in the file would be `["'asd", "ask", "asp", "asq"]` then you can load it an an actual python list and see the length of it with the `len()` function. Also, I wouldnt name your module `len.py` because `len` is a built in python function – bherbruck May 13 '20 at 17:56

3 Answers3

2

Use:

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')
Shubham Sharma
  • 38,395
  • 6
  • 14
  • 40
0
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)))

I updated the code to use the with statement from another answer. I also used some code from this answer (How can I convert this string to list of lists?) to (more?) correctly count nested lists.

vicente louvet
  • 264
  • 2
  • 9
  • Many thanks. I'm getting an error on line 10 when I run this: `fout.write(len(output_list)) TypeError: expected a character buffer object` – RedOrange May 13 '20 at 18:21
  • I updated the code to avoid that issue. the len() function returns an integer, but write() expects a string. It should run without error now. – vicente louvet May 13 '20 at 18:30
0

When python try to read a file using default method it generally treats content of that file as a string. So first responsibility is to type cast string content into appropriate content type for that you can not use default type casting method.

You can use special package by the name ast to type cast the data.

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()
Swapnil Pote
  • 126
  • 5