Tania
Tania

Reputation: 1925

CSV'ify a variable

I have a python variable that holds a string ready to be converted into a csv file. This is what my variable contains:-

myvar="ID,Name\n1001,Tania\n1002,Geraldina"

How do I make this variables into a csv file? I dont want the "\n"s and the "'s. Instead I want real line breaks..

EG:This is what I want inside my csv file (myvar.csv)

ID,Name
1001,Tania
1002,Geraldina

I tried this:

with open("myvar.csv","w+") as out:
    json.dump(myvar,out)

But it just inserts the string as is. Can anyone point me in the right direction? Thanks in advance.

Upvotes: 0

Views: 146

Answers (3)

martineau
martineau

Reputation: 123423

Pretty easily:

myvar = "ID,Name\n1001,Tania\n1002,Geraldina"

with open('myvar.csv', 'w') as csvfile:
    csvfile.write(myvar+'\n')

Upvotes: 1

bravmi
bravmi

Reputation: 507

for row in csv.reader(io.StringIO(myvar)):
    print(row)

It's for python3, for python2 it would be StringIO.StringIO.

Basically instead of actual file you're using file-like object.

With writing:

In [170]: with open('myvar.csv', 'w') as f:
   .....:     writer = csv.writer(f)
   .....:     for row in csv.reader(io.StringIO(myvar)):
   .....:         writer.writerow(row)

upd. Okay I'm overthinking it.. all you really need is just write to file, no csv functionality, since you already have "csv" data in your string. Just as @Avinash wrote. So f.write is good enough.

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174696

Your variable is already in csv format. Just write the variable contents into the csv file.

myvar="ID,Name\n1001,Tania\n1002,Geraldina"
with open("myvar.csv", "w") as w:
    w.write(str(myvar))

\n in the myvar is a real new line character not a literal \n

Upvotes: 3

Related Questions