python - convert csv to a string variable -
i beginner in python. need following
i have comma separated csv file, eg
a,b,c d,e,f g,h,i
i need convert string variable eg s='a,b,c\n,d,e,f\n,g,h,i\n'
i tried something, 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(): row in reader: v=','.join(row) a=csv2str()
you don't need csv module that. call read
method of file object read in lines 1 string:
with open(filename) 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 repr
of string because print of string i.e. print(a)
not show newline character \n
, show string in different lines.
Comments
Post a Comment