6

I am not sure what the problem is here. I have a csv file I want to filter. I want to remove all lines starting with '@' and all lines where the third column is the string 'chrM'. Im basically setting my code up to be like the answer here:

TypeError: expected a character buffer object

But Im getting an error.

import re
import csv

inputSamFile = 'excerpt'
outSamFile = 'filternoM'

with open(inputSamFile) as inputSam, open(outSamFile, 'wt') as outSam:
    inputSamCont = csv.reader(inputSam, delimiter = '\t')
    outSamCont = csv.writer(outSam, delimiter = '\t')
    for line in inputSamCont:
        if line[0].startswith('@'):
            continue
        elif line[2] == 'chrM':
            continue
        else:
            outSamCont.write(line)

Traceback (most recent call last): File "filterMito.py", line 19, in outSamCont.write(ProcessLine(line)) AttributeError: '_csv.writer' object has no attribute 'write'

What am I doing wrong

Community
  • 1
  • 1
von Mises
  • 266
  • 1
  • 6
  • 17

2 Answers2

5

You may be looking for .writerow().

I also ran into this problem, as the documentation I was following used .write(), but csv.writer objects use .writerow().

code4meow
  • 66
  • 1
  • 3
  • 2
    I have the same issue but with `writeheader` I'm copying the name from the documentation, how is it that it doesn't exist? – Charlie Parker Jan 30 '17 at 21:52
2

The error tells you everything you need to know.

AttributeError: '_csv.writer' object has no attribute 'write'

In your code, you create the object:

outSamCont = csv.writer(outSam, delimiter = '\t')

then try to call the .write() method:

outSamCont.write(line)

(or, as it is in the traceback

outSamCont.write(ProcessLine(line)) 

I'm not sure why you have posted different code to what you're running).

However, that object, a csv.writer, does not have the method write, hence the error message. See the documentation for csv.writer objects for the list of methods they do have, and choose the appropriate one.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437