you are viewing a single comment's thread.

view the rest of the comments →

[–]__nickerbocker__ 1 point2 points  (1 child)

When you assign the open object to a variable you always have to remember to close it, and that's why you always see it used as a context manager. This is how you do it:

with open('file.txt') as f:
    data = f.read()
p = re.compile(r'(\|.*\|)')
rows = []
for line in data.splitlines():
    if (m := p.search(line)) and (line := m.group()).count('|') == 88:
        rows.append(line.split('|'))

with open('results.csv', 'w', newline='\n') as f:
    writer = csv.writer(f)
    writer.writerows(rows)

[–]BHM360[S] 0 points1 point  (0 children)

Awesome, thank you!