Tezi
Tezi

Reputation: 9

How to write a sentence into a CSV file using Python

I have a sentence like !=This is great

How do I write the sentence into a .CSV file with "!" in the first column and "This is great" in another column?

Upvotes: 0

Views: 1588

Answers (3)

Darren Christopher
Darren Christopher

Reputation: 4821

Of course, you could write using standard io with open() and manually write with comma delimiter for each line, but python has csv standard library that will help you with this. You could specify the dialect

In [1]: import csv   

In [2]: sentence="!=This is great"   

In [3]: with open("test.csv", "w", newline='') as f: 
   ...:     my_csvwriter = csv.writer(f) 
   ...:     my_csvwriter.writerow(sentence.split("=")) 

With multiple data, assuming it's in list, you could iterate through it when writing.

with open("test.csv", "w", newline='') as f: 
     my_csvwriter = csv.writer(f)
     for sentence in sentences:
         my_csvwriter.writerow(sentence.split("="))

This library helps handling comma in a sentence, instead of handling it yourself. For instance you have:

sentence = "!=Hello, my name is.."
with open("test.csv", "w", newline='') as f: 
     my_csvwriter = csv.writer(f)
     my_csvwriter.writerow(sentence.split("="))

# This will be written: !,"Hello, my name is.."
# With that quote, you could still open it in excel without confusing it
# and it knows that `Hello, my name is..` is in the same column

Upvotes: 0

Derek Eden
Derek Eden

Reputation: 4638

split the text, and write it to an output file:

text  = open('in.txt').read() #if from input file
text = '!=This is great' #if not from input file

with open('out.csv','w') as f:
    f.write(','.join(text.split('=')))

output:

!,This is great

if you have multiple lines, you will have to loop through the input file and split each one

Upvotes: 1

Aniket Bote
Aniket Bote

Reputation: 3574

You can use pandas to_csv method

code:

import pandas as pd

col1 = []
col2 = []
f = '!=This is great'

l1 = f.split('=')
col1.append(l1[0])
col2.append(l1[1])

df = pd.DataFrame()
df['col1'] = col1
df['col2'] = col2
df.to_csv('test.csv')

Upvotes: 1

Related Questions