Skip to content Skip to sidebar Skip to footer

How To Get A List Of Tuples From Several Text Files?

I want to access .txt files in 46 subdirectories and extract the number of 0s and 1s in the text of each file. So far I've written this code: from pathlib import Path def count_0s

Solution 1:

There are couple mistakes in your function:

  • you've added some unnecessary square brackets (splitlines() already returns a list)
  • you don't iterate over characters, but over lines

Here is a corrected function:

def count_0s(paths):
  zeros_list = []
  ones_list = []
  forpin paths:
    zeros = 0
    ones = 0forlinein p.read_text().splitlines():
        forcin line:
            if c == '0':
                zeros += 1else:
                ones += 1
    zeros_list.append(zeros)
    ones_list.append(ones)
  return zeros_list, ones_list

Be aware that this is probably a very inefficient way of counting 0 and 1. For example just using line.count('0') instead of a for loop can increase the speed by a factor of 10.

Post a Comment for "How To Get A List Of Tuples From Several Text Files?"