简体   繁体   中英

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?

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')

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM