0

I am trying to write some text onto csv file. When I open it each letter is taking a cell. But I want each string to be in a cell. How do I do it. I am using python 2.7.10

Here is the simple code:

with open("output.csv",'wb') as f:
   writer = csv.writer(f, dialect='excel')
   writer.writerows('Apples:10 Mangoes:15 bananas:20')

I want output to be like this(total 6 cells)

Apples    10     Mangoes    15    Bananas    20

3 Answers 3

2

You need to make a couple changes. First, instead of writerows, utilize writerow. Second, you need to pass a list of elements instead of a string:

writer.writerow(['Apples','10','Mangoes','15','bananas','20'])

This will create a document that looks like this:

Excel output

Sign up to request clarification or add additional context in comments.

Comments

2

First, you should properly format your string:

Apples:10 Mangoes:15 bananas:20

Should be:

Apples,10,Mangoes,15,bananas,20

Then you can write a CSV which is easily imported into excel.

Second, if your final destination is writing excel files you should take a look at Pandas to export your data to excel, it has the convenient method:

pandas.DataFrame.to_excel

If your data is simpler, you can work directly with xlswriter.

Comments

1

You can simply split your long string into every row you want :

    my_str = 'Apples:10 Mangoes:15 bananas:20'
    writer.writerow( my_str.replace(':',' ').split() )

which will put spaces everywhere you want your string to split and then split it.

1 Comment

I need to write several rows of the same data. I see only one row which is being written onto file though I am looping over it. Please suggest.

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.