我实际上是尝试使用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
有什么建议吗?谢谢!
答案 0 :(得分:0)
您有两个冗余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
Folliwing OP编辑:
错误告诉您f
没有__exit__
方法,因此无法用作上下文管理器。这是因为,正如Steve Jessop评论的那样,你忘记了open()