Skip to content
Advertisement

Python CSV returning individual characters, expecting strings

This program uses Python’s CSV module to process a stream containing a CR/LF delimited list of comma separated values (CSV). Instead of getting a list of strings, with each string representing the text that appears between the delimiters (the commas), I’m getting a list of characters. The program uses subprocess.run() to return a stream containing rows of data separated by commas and newlines (CSV). The returned stream is printed and this output appears as expected (i.e. formatted as CSV). The program:

JavaScript

The output from the print(ps.stdout) statement:

JavaScript

And the some of the output from the for loop:

JavaScript

What I was expecting was this:

JavaScript

Why is row a list of characters and not a list of strings?

Advertisement

Answer

It’s returning bytes from stdout, not a file. When you loop over bytes, you get each instead of what you want. Instead, decode then split on newlines then loop over it.

JavaScript

This could be passed to csv reader. For example:

JavaScript

You could also make a temp file from out subprocess stdout like so:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement