Python的AttributeError问题

时间:2016-08-12 04:02:04

标签: python python-3.x csv with-statement

如果我运行具有此代码的文件,我没有问题,一切顺利。 我现在在另一个文件中调用此类,出于某种原因我收到此错误:

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__

我不明白为什么它在原始文件中工作而不是我从另一个文件中调用它。我查看了我的错误消息并found this question但是当我尝试配置我的代码以匹配时,我无法弄清楚如何在我的情况下应用它。我认为这主要是因为我不了解实际的错误。

这是我的代码:

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

1 个答案:

答案 0 :(得分:0)

您的问题是您传递的字符串为 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__

打开 self.temp1

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)

此外,我认为 self.acct 是一个整数,或者 itemgetter 逻辑不起作用。