Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python read multible text files as list in a class then iterate over them in another class

I have a folder named "filters". Here I am putting multible text files. I am building a class named ReadFilesToList that:

  1. Opens the directory "filters"
  2. Creates a list of text files into variable "filenames_list"
  3. Read all text files from "filenames_list" into variable "filters_list"

When I call the class I want a list of the content of the text files, so I can use it later in my program.

This is what I get when I run my program:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['2|Emil|Emma', '3|Noah|Ella', '4|Oliver|Maia', '5|Philip|Olivia', '1|Noah|Alice', '2|William|Maja', '3|Hugo|Elsa', '4|Lucas|Astrid', '5|Liam|Wilma']
['2|Emil|Emma', '3|Noah|Ella', '4|Oliver|Maia', '5|Philip|Olivia', '1|Noah|Alice', '2|William|Maja', '3|Hugo|Elsa', '4|Lucas|Astrid', '5|Liam|Wilma']
['2|Emil|Emma', '3|Noah|Ella', '4|Oliver|Maia', '5|Philip|Olivia', '1|Noah|Alice', '2|William|Maja', '3|Hugo|Elsa', '4|Lucas|Astrid', '5|Liam|Wilma']
['2|Emil|Emma', '3|Noah|Ella', '4|Oliver|Maia', '5|Philip|Olivia', '1|Noah|Alice', '2|William|Maja', '3|Hugo|Elsa', '4|Lucas|Astrid', '5|Liam|Wilma']
['2|Emil|Emma', '3|Noah|Ella', '4|Oliver|Maia', '5|Philip|Olivia', '1|Noah|Alice', '2|William|Maja', '3|Hugo|Elsa', '4|Lucas|Astrid', '5|Liam|Wilma']
['2|Emil|Emma', '3|Noah|Ella', '4|Oliver|Maia', '5|Philip|Olivia', '1|Noah|Alice', '2|William|Maja', '3|Hugo|Elsa', '4|Lucas|Astrid', '5|Liam|Wilma']
['2|Emil|Emma', '3|Noah|Ella', '4|Oliver|Maia', '5|Philip|Olivia', '1|Noah|Alice', '2|William|Maja', '3|Hugo|Elsa', '4|Lucas|Astrid', '5|Liam|Wilma']
['2|Emil|Emma', '3|Noah|Ella', '4|Oliver|Maia', '5|Philip|Olivia', '1|Noah|Alice', '2|William|Maja', '3|Hugo|Elsa', '4|Lucas|Astrid', '5|Liam|Wilma']

This is what I want:

2|Emil|Emma
3|Noah|Ella
4|Oliver|Maia
5|Philip|Olivia
1|Noah|Alice
2|William|Maja
3|Hugo|Elsa
4|Lucas|Astrid
5|Liam|Wilma

Below is a overview of the program with the code.

enter image description here

norwegian.txt

Number      Boy     Girl
2           Emil    Emma
3           Noah    Ella
4           Oliver  Maia
5           Philip  Olivia

swedish.txt

Number  Boy         Girl
1       Noah        Alice
2       William     Maja
3       Hugo        Elsa
4       Lucas       Astrid
5       Liam        Wilma

main.py

from ReadFilesToList import ReadFilesToList

#myList = ReadFilesToList()
#for data in myList:
#    print(data)

#print(ReadFilesToList())

for c in ReadFilesToList():
    print(c)

ReadFilesToList.py

import os
import re


class ReadFilesToList:

    # Initialize class -------------------------------- #
    def __init__(self):
        self.current = 0
        self.high = 0

        self.filenames_list = [] # Generate list of all txt files to read
        self.filters_list = [] # Generate list of all keywords separated with |

        # Find all filters in "filters" directory
        for filename in os.listdir("filters"):
            with open(os.path.join("filters", filename), 'r') as f: # open in readonly mode
                #print(filename)
                self.filenames_list.append(filename)

        # Read filters
        for filename in self.filenames_list:
            #print(filename)

            # Read filter
            f = open('filters/' + filename)  # Open file on read mode
            data_list = f.read().splitlines()  # List with stripped line-breaks
            f.close()  # Close file

            # Remove first line
            del data_list[0]

            # Loop trough list and remove double tabs
            count = 0
            for line in data_list:
                data_list[count] = re.sub("[\t ]{2,}", "|", line) # Make separator |
                data_list[count] = data_list[count].replace("\t", "|") # Make separator |


                # Append to existing filters list
                self.filters_list.append(data_list[count])

                count += 1

        # Count number of items in data_list and use it as high
        self.high = len(self.filters_list)

    # Call class from other class --------------------- #
    def __iter__(self):
        return self

    # Next for a for loop over keywords --------------- #
    def __next__(self): # Python 2: def next(self)
        self.current += 1
        if self.current < self.high:
            return self.filters_list
        raise StopIteration

    # Call class from other class --------------------- #
    def __call__(self):
        return self.filters_list

>Solution :

Try this:

def __call__(self):
    return '\n'.join(self.filters_list)

Now when you call your class (and you print the result) you get:

>>> x = ReadFilesToList()
>>> print(x())
2|Emil|Emma
3|Noah|Ella
4|Oliver|Maia
5|Philip|Olivia
1|Noah|Alice
2|William|Maja
3|Hugo|Elsa
4|Lucas|Astrid
5|Liam|Wilma

Otherwise, if you want to keep your implementation of the __call__ method, then you would do the following:

>>> x = ReadFilesToList()
>>> print(*x(), sep='\n')
2|Emil|Emma
3|Noah|Ella
4|Oliver|Maia
5|Philip|Olivia
1|Noah|Alice
2|William|Maja
3|Hugo|Elsa
4|Lucas|Astrid
5|Liam|Wilma
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading