1

I'd like to figure out how I should use a class to read input from a file so that I can use that data in other classes. If I read input from a file into a list, should I pass that to another class that needs that to use that information?

Right now I have:

import sys

class FileReader:
    """Reads a file"""
    def __init__(self):
        input = ''
        try:
            with open(sys.argv[1], 'r') as inFile:
                input = inFile.readline()
                print(input)
        except IndexError:
            print("Error - Please specify an input file.")
            sys.exit(2)

def main():
    x = FileReader()

if __name__ == "__main__":
    main()

I thought about making some kind of list to hold strings from the file, but I'm not sure whether that should be global or not.

5
  • 3
    Don't tie your class to the command line arguments - You should add a file_path parameter to __init__ and pass in sys.argv[1] or a file path obtained however else you like when creating an instance of FileReader Commented Dec 3, 2012 at 18:15
  • Also don't catch the exception and simply call sys.exit() - let the calling code catch the exception and decide what to do. You can re-raise with a more informative exception rather than printing an error message (not sure what's the norm here though) Commented Dec 3, 2012 at 18:21
  • @MrE Thanks for the tips! Why should I not tie my class to command line arguments? I'm not sure I understood the reason. Commented Dec 3, 2012 at 18:31
  • 2
    @ChrisHarris I think what people are saying is that command line processing should be handled by something like argparse and validation should occur there... then the classes work on data passed to them from that... It means that your classes are more usable for data from arbitary sources (ie: you want to take a filename from a database result) - at the basic level - def(a, b) shouldn't care where a and b come from as long as it can work them. Commented Dec 3, 2012 at 18:45
  • You seem to be wondering what data structure you need for your program. The answer depends on the algoritm you want to implement. Commented Dec 3, 2012 at 19:28

1 Answer 1

3

If all you're trying to do is read the file line by line, something like the following would work just fine (exception handling omitted).

>>> path = '/path/to/file.txt'
>>> with open(path, 'r') as f:
...     lines = [l for l in f]

You can then pass around lines as necessary.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.