tags:

views:

78

answers:

2

I found this class to take a space delimited file and if there are multiple spaces, they will be treated as a single separator. How do I see the effects of this on a file?

class FH:

    def __init__(self, fh):
        self.fh = fh

    def close(self):
        self.fh.close()

    def seek(self, arg):
        self.fh.seek(arg)

    def fix(self, s):
        return ' '.join(s.split())

    def next(self):
        return self.fix(self.fh.next())

    def __iter__(self):
        for line in self.fh:
            yield self.fix(line)

so how do I see this work on a file? I've created a file with multiple spaces to see it in action.

I've done this:

In [31]: FH('classfhtry.csv')
Out[31]: 

In [32]: r = FH('classfhtry.csv')

In [33]: r
Out[33]: 

In [34]: print r
-------> print(r)


In [35]: f = open(r)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/blahblahblah/Documents/Programming/EXERCISES/piece.py in ()
----> 1 
      2 
      3 
      4 
      5 

TypeError: coercing to Unicode: need string or buffer, instance found

I want to see my class in action! Thanks for any 2cents!

+5  A: 

Looks like this class takes a file (not a file name) in the initializer. Try:

r = FH(file('classfhtry.csv', 'r'))
for line in r:
    print line
dcrosta
In [36]: r = FH(file('classfhtry.csv', 'r'))In [37]: for line in r: ....: print r ....: ....: <__main__.FH instance at 0x987590c><__main__.FH instance at 0x987590c><__main__.FH instance at 0x987590c>I don't get to see whats in the file. Is there any way I can access <__main....etc.?
Pete
Whoops, I made a typo... should be "print line" not "print r" (corrected)
dcrosta
it works!!!!!!!! thanks!
Pete
A: 

dcrosta is correct. The class expects a space delimited contents in the file. Have a file like:

somefile.txt

one two
three four
five six

And follow the method as suggested above. The class is an iterator (it yields the lines from the file obj). So, the way to access to the file is the iterate through the contents.

Senthil Kumaran
In [36]: r = FH(file('classfhtry.csv', 'r')) In [37]: for line in r: ....: print r ....: ....: <__main__.FH instance at 0x987590c> <__main__.FH instance at 0x987590c> <__main__.FH instance at 0x987590c> I don't get to see whats in the file. Is there any way I can access <__main....etc.?............I tried it though...hmmm...how do I get to see it work?
Pete
Have a look at this paste http://codepad.org/s3PPnNvI I have simulated file open function. But at the place. you could given open('filename') and have the same effect.
Senthil Kumaran