Reputation: 1
I am trying to take a text document and write each word separately into another text document. My only issue is with the code I have sometimes the words aren't all split based on the white space and I'm wondering if I'm just using .split wrong? If so, could you explain why or what to do better?
Here's my code:
list_of_words = []
with open('ExampleText.txt', 'r') as ExampleText:
for line in ExampleText:
for word in line.split(''):
list_of_words.append(word)
print("Done!")
print("Also done!")
with open('TextTXT.txt', 'w') as EmptyTXTdoc:
for word in list_of_words:
EmptyTXTdoc.write("%s\n" % word)
EmptyTXTdoc.close()
This is the first line in the ExampleText text document as it is written in the newly created EmptyTXTdoc:
Submit
a personal
statement
of
research
and/or
academic
and/or
career
plans.
Upvotes: 0
Views: 1410
Reputation: 690
.split('')
Will not remove a space because there isn't a space in between the two apostrophes. You're telling it to split on, well, nothing.
Upvotes: 0
Reputation: 16184
Use .split()
(or .split(' ')
for only spaces) instead of .split('')
.
Also, consider sanitizing the line
with .strip()
for every iteration of the file, since the line is accepted with a newline (\n
) in its end.
Upvotes: 1