6

I am a beginner in python. I need help with the following

I have a comma separated csv file, eg

a,b,c
d,e,f
g,h,i

I need to convert to a string variable eg s='a,b,c\n,d,e,f\n,g,h,i\n'

I tried something, but i am going wrong somewhere.

import os
import csv
Filename=r"c:\Users\das\Desktop\a.csv"
z=open(Filename, 'r')
reader=csv.reader(Filename.split('\n'),delimiter=',')
def csv2str():
 for row in reader:
 v=','.join(row)
a=csv2str()
asked Nov 6, 2016 at 0:37

1 Answer 1

9

You don't need the csv module to do that. Just call the read method of the file object to read in all the lines as one string:

with open(filename) as f:
 s = f.read() + '\n' # add trailing new line character
print(repr(s))
# 'a,b,c\nd,e,f\ng,h,i\n'

I'm printing the repr of the string because a print of the string itself i.e. print(a) will not show the newline character as \n, but will show the string in its different lines.

answered Nov 6, 2016 at 0:41
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, was looking for that !!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.