0

If I run the file that has this code, I have no problems and everything is smooth. I'm now calling this class in another file and for some reason I get this error:

Traceback (most recent call last):
  File "C:\users\cato\work\reports\runReports.py", line 524, in runAllAdmis
    self.sortAcctCol()
  File "C:\users\cato\work\reports\runReports.py", line 553, in sortAcctCol
    with open(self.inFile, "r") as self.oi, self.temp1:
AttributeError: __exit__

I don't understand why it's working in the original file and not when I call it from another. I looked up my error message and I found this question but when I tried configuring my code to match, I couldn't figure out how to apply it in my situation. I think this mostly due to me not understanding the actual error.

This is my code:

def sortAcctCol(self):

    with open(self.inFile, "r") as self.oi, self.temp1:
        r = csv.reader(self.oi)
        w = csv.writer(self.temp1)

        self.header = next(r)

        self.sortedCol = sorted(r, key=operator.itemgetter(self.acct), reverse=False)

        for row in self.sortedCol:
            w.writerow(row)

    self.temp1 = self.temp1.name
Community
  • 1
  • 1
catoejr
  • 13
  • 5
  • I would expect `with open(self.inFile, "r") as self.oi, self.temp1` to give a `NameError`. Anyway, why are you using instance attibutes as your variables in this statement? – juanpa.arrivillaga Aug 12 '16 at 04:14
  • 1
    I'm not sure what are you trying to achieve with this line `with open(self.inFile, "r") as self.oi, self.temp1: ` but you can not have multiple variables like that. Please see: [Multiple variables in Python 'with' statement](http://stackoverflow.com/questions/893333/multiple-variables-in-python-with-statement) and [Specification: The 'with' Statement section of PEP 343](https://www.python.org/dev/peps/pep-0343/) – Lafexlos Aug 12 '16 at 06:33
  • @PadraicCunningham can you elaborate on TemporaryFiles vis a vis multiple assignment targets in the with statement? – juanpa.arrivillaga Aug 12 '16 at 09:52

1 Answers1

0

Your problem is you are passing a string as self.temp1:

In [3]:   with open("out.log", "r") as read, "foo.txt":
   ...:     pass
   ...: 
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-9088e1884eea> in <module>()
----> 1 with open("out.log", "r") as read, "foo.txt":
      2   pass
      3 

AttributeError: __exit__

open self.temp1 also:

def sort_acct_col(self):
    with open(self, "r") as read, open(self.temp1, "w") as write:
        r = csv.reader(read)
        next(r)
        sorted_col = sorted(r, key=operator.itemgetter(self.acct), reverse=False)
        csv.writer(write).writerows(sorted_col)

Also I presume self.acct is an integer or your itemgetter logic won't be working.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321