0

I've a nested list like Python_List below and I want to make a .csv like below:

    Python_List|->  .csv
    [['2','4'],|     2,4   
     ['6','7'],|     6,7
     ['5','9'],|     5,9
     ['4','7']]|     4,7

So far I'm using this code:

Python_List=[['2','4'],  ['6','7'], ['5','9'], ['4','7']]
with open('test.csv','w') as f:
    for i in range(0,len(Python_List)):
        f.write('%s,%s\n' %(Python_List[i][0],Python_List[i][1]))

Are there any alternatives more efficient?

2
  • 1
    A remark on your for-loop: You do not need to loop through indexes. Instead loop over the elements themselves for l in Python_List:, then the next line reduces to f.write('%s,%s\n' % tuple(l)). Anyway you should use csv.writer. Commented Jan 3, 2014 at 10:36
  • @Nabla thanks this is a very useful trick feel free to post an answer is a nice way to do what I want! Commented Jan 3, 2014 at 10:45

3 Answers 3

4

Consider using the writer method of the csv module.

It may not be more efficient but it will be easier to understand.

For Example

import csv
with open('test.csv', 'w') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=',')
    csvwriter.writerows(Python_List)
Sign up to request clarification or add additional context in comments.

Comments

2
>>> i = [['2','4'],  ['6','7'], ['5','9'], ['4','7']]
>>> with open('test.csv','w') as f:
...    writer = csv.writer(f)
...    writer.writerows(i)
... 
>>> quit()
$ cat test.csv
2,4
6,7
5,9
4,7

Comments

1

You can csv module and its writer method, like this

pyList = [['2','4'],  ['6','7'], ['5','9'], ['4','7']]
import csv
with open('Output.txt', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=',')
    map(csvwriter.writerow, pyList)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.