TypeError: expected a character buffer object

What the error message is saying is that you can't write a list to a file, only "a character buffer object", meaning a string or something else that acts a lot like a string.

If you just want to write the list to the file in the same way you'd print them to the console, you can write str(thefile) or repr(thefile) (or even use the redirect syntax in print instead of using file.write).

But you're using the csv module to read the input, and presumably want the output in the same format, so you probably want to use csv to write it too.

You're reading like this:

list(csv.reader(open(filename, 'rb'), delimiter=',', quotechar='"'))[1:]

So write like this:

csv.writer(open('foo.csv', 'wb'), delimiter=',', quotechar='"').writerows(thefile)

I should mention that I wouldn't structure the code like this in the first place; I'd do something like this:

with open('input.csv', 'rb') as infile, open('output.csv', 'wb') as outfile:
  incsv = csv.reader(infile, delimiter=',', quotechar='"')
  outcsv = csv.writer(outfile, delimiter=',', quotechar='"')
  incsv.read() # skip first line
  for line in incsv:
    if line[3] != '':
      outcsv.write(ProcessLine(line))

You can't write a list to a file; you can only write a string. Convert the list to a string in some way, or else iterate over the list and write an element at a time. Or you're using the csv module, use that to write to the file.

Calling something other than a file (such as a list) thefile is bound to lead to confusion, just by the way.


thefile is a list of lists, not a character buffer.

for sublist in thefile:
    f.write("".join(sublist))  # perhaps

there is some bad here, using global, naming a list thefile, ...

(The correct answer is abarnert's).

Tags:

Python