Python Forum

Full Version: write split words of sentence to file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
When I test the split on Python's IDLE, I get a list of words, for example:
Python 3.6.5 (default, Apr  1 2018, 05:46:30) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> sample_text='some sample text'
>>> sample_text.split()
['some', 'sample', 'text']
But when attempting the same to write to a file
import csv
import pathlib
some_text='some sample text'
target_path = pathlib.Path('python/t.txt')
with target_path.open('w+', newline='\n') as target_file:
    writer = csv.writer(target_file)
    for t in some_text.split():
        writer.writerow(t)
the resulting file output appears as follows:
$ cat ../t.txt
s,o,m,e
s,a,m,p,l,e
t,e,x,t
Can somebody help explain the difference?
Thanks
Maybe you intended
writer.writerow(some_text.split())
instead of your last two lines?