Question

Using the code below, I'm getting the correct information to the file - kind of. Here's the code:

filename = raw_input('What would you like to name the file? ')

import csv

data = [frames]
out = csv.writer(open(filename,"w"), delimiter=' ',quoting=csv.QUOTE_MINIMAL)
out.writerows(data)

This generates something that looks like this in a text file:

"[255   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0]" "[  0 171 171 171 171 171 171 171 171 171 171 171 171 171 171 171 171 171
 171 171]" 

I would like the information to look like this:

255 255 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 []0 255 255 255 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

The 2 brackets represents a character that indicates a new row of information. It's a little rectangle on my text editor and I'm unsure of what the character is.

So, how do I get rid of the quotes and brackets and use this other character?

EDIT:

I tried using the code below and got the following error:

Traceback (most recent call last):   
  File "(stdin)", line 1, in (module)   
  File "backandforth3.py", line 154, in (module)
    out.write(' '.join(frame)) 
Type Error: sequence item 0: expect string, numpy.int32 found
Was it helpful?

Solution

I'm assuming you're using Notepad as your text editor? Unix-style newlines (\n) show up as boxes in Notepad because it only supports Windows newlines (\r\n). That said, this should provide the output you're expecting:

filename = raw_input('What would you like to name the file? ')

with open(filename, 'wb') as out:
    for frame in frames:
        out.write(' '.join(str(num) for num in frame))
        out.write('\r\n')

There's no reason to wrap frames in another list; assuming that variable is a list of lists of numbers, as the expected output would indicate, this should work fine.

Also, if you absolutely have to have the "boxes" that you described in the output, replace '\r\n' with '\n'.

OTHER TIPS

If frames is a numpy array than you could use numpy.savetxt() function:

numpy.savetxt(filename, frames)

To fix your csv code open the file in binary mode wb to avoid corrupting end of lines, and don't wrap frames in another list it seems to be already a 2D array:

import csv

with open(filename,"wb") as f:
    writer = csv.writer(f, delimiter=' ', quoting=csv.QUOTE_MINIMAL)
    writer.writerows(frames)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top