Python csv编写器"AttributeError:__ exit__";问题 [英] Python csv writer "AttributeError: __exit__" issue

查看:132
本文介绍了Python csv编写器"AttributeError:__ exit__";问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在制表符分隔的.csv中写入三个变量,每次脚本在字典中的键值上进行迭代时,都会附加值.

I have three variables I want to write in a tab delimited .csv, appending values each time the script iterates over a key value from the dictionary.

当前脚本调用一个命令,将标准输出正则表达式为out,然后将三个已定义的正则表达式组分配给各个变量,以写入标记为firstsecondthird的.csv.运行以下脚本时出现__exit_错误.

Currently the script calls a command, regex the stdout as out then assigns the three defined regex groups to individual variables for writing to .csv labeled first second and third. I get a __exit_ error when I run the below script.

/note我已经在csv.writer上进行了阅读,但对于是否可以将多个变量实际写入一行,我仍然感到困惑.

/note I've read up on csv.writer and I'm still confused as to whether I can actually write multiple variables to a row.

感谢您可以提供的任何帮助.

Thanks for any help you can provide.

 import csv, re, subprocess

 for k in myDict:
     run_command = "".join(["./aCommand", " -r data -p ", str(k)])
     process = subprocess.Popen(run_command,
                                shell=True,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
     out, err = process.communicate()
     errcode = process.returncode
     pattern = re.compile('lastwrite|(\d{2}:\d{2}:\d{2})|alert|trust|Value')
     grouping = re.compile('(?P<first>.+?)(\n)(?P<second>.+?)([\n]{2})(?P<rest>.+[\n])', 
                           re.MULTILINE | re.DOTALL)


    if pattern.findall(out):         
        match = re.search(grouping, out)
        first = match.group('first')
        second = match.group('second')
        rest = match.group('rest')

     with csv.writer(open(FILE, 'a')) as f:
        writer = csv.writer(f, delimiter='\t')
        writer.writerow(first, second, rest)

在注释中要求发布整个追溯,请注意,追溯中列出的行将与上面的代码不匹配,因为这不是整个脚本.

Requested in the comments to post entire traceback, note the line listed in traceback will not match the above code as this is not the entire script.

Traceback (most recent call last):
File "/mydir/pyrr.py", line 60, in <module>
run_rip()
File "/mydir/pyrr.py", line 55, in run_rip
with csv.writer(open('/mydir/ntuser.csv', 'a')) as f:
AttributeError: __exit__

答案:使用以下注释,我可以将其编写如下.

Answer: Using the below comment I was able to write it as follows.

f = csv.writer(open('/mydir/ntuser.csv', 'a'),
                       dialect=csv.excel,
                       delimiter='\t')
f.writerow((first, second, rest))

推荐答案

错误非常明显. with语句采用上下文管理器,即具有__enter____exit__方法的对象,例如open返回的对象. csv.writer不提供这样的对象.您还尝试两次创建编写器:

The error is pretty clear. The with statement takes a context manager, i.e., an object with an __enter__ and an __exit__ method, such as the object returned by open. csv.writer does not provide such an object. You are also attempting to create the writer twice:

with open(FILE, 'a') as f:
    writer = csv.writer(f, delimiter='\t')
    writer.writerow(first, second, rest)

with ... f:就像try...except...finally一样,无论发生什么情况,它都保证f是关闭的,除非您不必键入它. open(...)返回一个上下文管理器,该上下文管理器在您无需键入的finally块中调用了__exit__方法.那就是您的例外所抱怨的. open返回正确定义了__exit__的对象,因此可以处理with块中的正常退出和异常. csv.writer没有这种方法,因此您不能在with语句本身中使用它.正如我向您展示的那样,您必须在语句后的with块中执行此操作.

The with ... f: is like a try...except...finally that guarantees that f is closed no matter what happens, except you don't have to type it out. open(...) returns a context manager whose __exit__ method is called in that finally block you don't have to type. That is what your exception was complaining about. open returns an object that has __exit__ properly defined and can therefore handle normal exit and exceptions in the with block. csv.writer does not have such a method, so you can't use it in the with statement itself. You have to do it in the with block following the statement, as I've shown you.

这篇关于Python csv编写器"AttributeError:__ exit__";问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆