AttributeError: __exit__ while processing all files in directory

AttributeError: __exit__ while processing all files in directory

我实际上是在尝试使用 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

有什么建议吗?谢谢!

您有两个多余的 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 评论的那样,您忘记了 open()