7

I want to save my output as csv file with custom name and delimiter. I tried this code but now works for me.

out = open('out.csv', 'w')
for row in l:
for column in row:
    out.write('%d;' % column)
out.write('\n')
out.close()

Here is my data

100A7E54111FB143    
100D11CF822BBBDB    
1014120EE9CCB1E0    
10276825CD5B4A26    
10364F56076B46B7    
103D1DDAD3064A66    
103F4F66EEB54308    
104310B0280E4F20    
104E80752424B1C3    
106BE9DBB186BEC5    
10756F745D8A4123    
107966C82D8BAD8     

I want to save like this

input.csv
input_id data
number   107966C82D8BAD8 | 10756F745D8A4123 | 106BE9DBB186BEC5

The delmiter would be '|'.The data is in dtype:object

Any help will be appreciated.

2
  • 1
    Use the csv module. Commented Jan 30, 2016 at 9:51
  • 1
    Replace out.write('\n') to out.write(' | ') but your end char is ` | ` so detect end line iscoming(if is last element). Commented Jan 30, 2016 at 9:54

3 Answers 3

6

Use a writer for the CSV object instead:

import csv

with open('out.csv', 'w', newline='') as out:
    spamwriter = csv.writer(out, delimiter='|')
    spamwriter.writerow(column)

I have omitted your for loop

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

3 Comments

Sorry, i couldnt get the indentation correctly from my mobile. Markdown issues
I am getting the following error...Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: I/O operation on closed file
Make sure the for loop is within the scope of the with statement
3

One simple way is to use print of python 3.x, If you are using python 2.x then import print from future

from __future__ import print_function   #Needed in python 2.x 

print(value, ..., sep=' ', end='\n', file=sys.stdout)

1 Comment

just a hint, one can use unpacking here: print(*row, sep=' ', end='\n', file=sys.stdout)
1

You can use this snippet of code as an example. I did something similar in my program, creating a text file with a comma separator, no csv module involved. Not sure about newlines. I just used it for one line in my case...

        cachef_h = [a,b,c,d]
        f = open('cachef_h.txt', 'x')
           f.write(cachef_h[0])
           for column_headers in cachef_h[1:]:
           f.write(',' + column_headers)

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.