0

I am using Python 2.x on Win7.

My question is:

I got a list of numbers: angle = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and I would like to export the numbers to a csv file. So the csv should look like:

0 | 1 | 2 |...| 10 |

But so far what I got in csv file is:

[0 | 1 | 2 |...| 10] |

My code is:

angle = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ldsvp = open("C:\Controlled NP\\" + "LDS1.csv", 'ab')
with open('LDS1.csv', 'wb') as output:
   ldsvp.write('Angle' + ',' + str(angle))
   ldsvp.write('\n')

So...any advice to remove the [ and ] from the csv file?

martineau
  • 119,623
  • 25
  • 170
  • 301
Amber.G
  • 1,343
  • 5
  • 12
  • 16
  • 2
    `','.join([str(a) for a in angle])` – Julien Jan 18 '18 at 01:07
  • Possible duplicate of [How to remove square brackets from list in Python?](https://stackoverflow.com/questions/13207697/how-to-remove-square-brackets-from-list-in-python) – eyllanesc Jan 18 '18 at 01:08
  • @Julien In these cases, I prefer the succinctness of `','.join(map(str, angle))` – juanpa.arrivillaga Jan 18 '18 at 01:12
  • Possible duplicate of [Print list without brackets in a single row](https://stackoverflow.com/questions/11178061/print-list-without-brackets-in-a-single-row) – Turn Jan 18 '18 at 01:14
  • So, just to be clear, when you do `str(my_list)`, it creates a string representation of the *list*, which will look a lot like the list literal you would write in source code. If you are actually writing a csv file, I suggest using the `csv` modules. – juanpa.arrivillaga Jan 18 '18 at 01:14

1 Answers1

0

As suggested by @juanpa.arrivillaga python has csv module which makes the job easier.

An example would be

import csv
import os

def csvWriter(file):
    if os.path.exists(file):
        mode = "ab"
    else:
        mode = "wb"

    with open(file, mode) as csvfile:
        writer = csv.writer(csvfile, dialect='excel')
        writer.writerow([rec for rec in range(1, 11)])

if __name__ == "__main__":
    csvWriter('names.csv')

The output looks like this

1,2,3,4,5,6,7,8,9,10
Varad
  • 920
  • 10
  • 25