Python csv writer "AttributeError: __exit__" problem

I have three variables that I want to write to a .csv delimited table, adding values ​​each time the script iterates over the key value from the dictionary.

Currently, the script calls the command, regex, stdout as out, then assigns the three defined regular expression groups to separate variables for writing to .csv with the first secondand label third. I get __exit_ error when I run below script.

/ note I read csv.writer, and I'm still confused about whether I can actually write multiple variables in a line.

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)

: , , , traceback, , 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__

: , .

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

. with , .. __enter__ __exit__, , open. csv.writer . :

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

with ... f: try...except...finally, , f , , , . open(...) , __exit__ finally , . , . open , __exit__ with. csv.writer , with. with , .

+5

Source: https://habr.com/ru/post/1629496/


All Articles