Search code examples
pythonoopsys

basic trouble opening a file with python object oriented programming script


I'm new to OOP and am having trouble writing and executing a basic script that will open and read a file.

I'm getting an error IOError: [Errno 2] No such file or directory: '--profile-dir' when I run this. What's wrong with this and how should I fix it?

class testing(object):

    def __init__(self, filename):
        self.filename = filename
        self.words = self.file_to_text()

    def file_to_text(self):
        with open(filename, "r") as file_opened:
            text = file_opened.read()
            words = text.split()
            return words

alice = testing("alice.txt").file_to_text()
print alice

Also, if I'd like to be able to make this executable from the command line, these tweaks should make it work, right?

import sys
...
alice = testing(sys.argv[1]).file_to_text()
print alice

line to actually input in command line to run it-----> ./testing.py alice.txt

thanks in advance guys.


Solution

  • Somewhere you have a filename = '--profile-dir' defined, that is being used in with open(filename, "r"), use with open(self.filename, "r") to use the actual attribute you have defined in the class:

    filename = "foob"
    class testing(object):  
        def __init__(self, filename):
            self.filename = filename
            self.words = self.file_to_text()
        def file_to_text(self):
            print(filename)
            with open(filename, "r") as file_opened:
                text = file_opened.read()
                words = text.split()
                return words 
    

    Output:

    foob
    IOError: [Errno 2] No such file or directory: 'foob'
    

    Your code will work fine using sys.argv once you make the change:

    import sys
    
    class testing(object):
        def __init__(self, filename):
            self.filename = filename
            self.words = self.file_to_text()
        def file_to_text(self):
            with open(self.filename, "r") as file_opened:
                text = file_opened.read()
                words = text.split()
                return words
    alice = testing(sys.argv[1]).file_to_text()
    print alice
    
    :~$ python main.py input.txt
    ['testing']
    

    If you want to use ./ put #!/usr/bin/env python at the top and chmod +x to make it executable.

    You can also avoid calling read and splitting using itertools.chain:

    from itertools import chain
    class testing(object):
        def __init__(self, filename):
            self.filename = filename
            self.words = self.file_to_text()
        def file_to_text(self):
            with open(self.filename, "r") as file_opened:
                return list(chain.from_iterable(line.split() for line in file_opened))