Python Forum
write split words of sentence to file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
write split words of sentence to file
#1
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
Reply
#2
Maybe you intended
writer.writerow(some_text.split())
instead of your last two lines?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  about write file wrong (Edit directly online) CNenfan 4 2,452 Jan-29-2021, 05:32 AM
Last Post: deanhystad
  Write to file emilng 1 1,680 Nov-08-2020, 08:44 PM
Last Post: Gribouillis
  Convert a sentence to pig latin SalsaBeanDip 4 3,149 Oct-04-2020, 01:45 AM
Last Post: SalsaBeanDip
  [split] how to read a specific row in CSV file ? laxmipython 2 8,801 May-22-2020, 12:19 PM
Last Post: Larz60+
  finding p's in words of a multi-line text file johneven 5 4,270 Jun-24-2019, 03:41 PM
Last Post: ThomasL
  [split] Please advise how to write this program Rmasson 4 3,081 Apr-20-2019, 01:53 AM
Last Post: Skaperen
  Homework - Read from/Write to file (renamed from Help help help) Amitkafle 1 2,981 Jan-11-2018, 07:24 AM
Last Post: wavic
  Reverse string sentence with for loop? BillGates 3 5,994 May-02-2017, 04:15 PM
Last Post: wavic
  function to write the contents of a webpage into a new file roadrage 4 5,961 Dec-01-2016, 09:28 PM
Last Post: snippsat
  Extract data csv file and write in another file alexgrand 3 5,062 Nov-14-2016, 06:54 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020