【问题标题】:AttributeError: __exit__ while processing all files in directoryAttributeError: __exit__ 同时处理目录中的所有文件
【发布时间】:2015-12-08 02:04:59
【问题描述】:

我实际上是在尝试使用 python 脚本处理当前工作目录中的每个文件。尽管我尽了最大努力,但在运行代码时仍会出现此错误:

File "script.py", line 9, in <module>
    with my_file as f:
AttributeError: __exit__

这是我的代码:

import os

for my_file in os.listdir(os.getcwd()):
    first = True;
    movie_id = 0;

    with my_file as f:
        for line in f:
            if first == False:
                sys.stdout.write(movie_id + "," + line);
            else:
                movie_id = line
                movie_id = movie_id[0:len(movie_id) - 2]
                first = False

有什么建议吗?谢谢!

【问题讨论】:

  • 您可能打算在my_file 上致电open()

标签: python io file-handling


【解决方案1】:

您有两个冗余的close()with: 套件负责处理。只是:

import os

for my_file in os.listdir(os.getcwd()):
    print file
    first = True;
    movie_id = 0;

    with open(my_file) as f:
    #    ^^^^^       ^
        for line in f:
            if first == False:
                sys.stdout.write(movie_id + "," + line);
            else:
                movie_id = line
                movie_id = movie_id[0:len(movie_id) - 2]
                first = False

以下 OP 编辑​​:

错误告诉您f 没有__exit__ 方法,因此不能用作上下文管理器。那是因为,作为 Steve Jessop 的 cmets,你忘记了 open()

【讨论】:

  • 我认为这可能是问题所在,但是,无论是否关闭,我仍然会遇到同样的错误,不过我会用更改来更新我的代码
猜你喜欢
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 2011-10-13
相关资源
最近更新 更多