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.

Ci3
  • 4,632
  • 10
  • 34
  • 44
  • 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` – YXD Dec 03 '12 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) – YXD Dec 03 '12 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. – Ci3 Dec 03 '12 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. – Jon Clements Dec 03 '12 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. – Janne Karila Dec 03 '12 at 19:28

1 Answers1

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.

Matt Briançon
  • 1,064
  • 16
  • 24