0

I'm trying to transform each word from a txt file so that the carriage return is removed, and then have the words printed out. However, there's an extra newline at the end when I run the code. I checked for any extra spaces in the code, but I'm not sure how to remove it.

This is what I typed in:

f = open("/home/pride_and_prejudice.txt").read()
for word in f.split("\n"):
     word_new = word.rstrip("\n")
     print(word_new)

This should give me:

It
is
a
truth
universally
acknowledged
that
a
single
man
in
possession
of
a
good
fortune
must
be
in
want
of
a
wife
However
little
known
the
feelings
or
views
of
such
a
man
may
be
on
his
first
entering
a
neighbourhood
this
truth
is
so
well
fixed
in
the
minds
of
the
surrounding
families
that
he
is
considered
as
the
rightful
property
of
some
one
or
other
of
their
daughters
InSync
  • 4,851
  • 4
  • 8
  • 30
  • What does the original file look like? – Mark Tolonen Mar 18 '23 at 04:43
  • What do you currently get? – Felix Fourcolor Mar 18 '23 at 04:44
  • If you split on `\n` there won't be any `\n` left to remove. To get individual words, you'd need to split on spaces. – Ouroborus Mar 18 '23 at 04:54
  • Welcome to Stack Overflow. "However, there's an extra newline at the end when I run the code" - no; there's an extra **empty string** at the end, because the *file contents* have a newline at the end and you make the list by splitting on newlines. The elements of the list **already don't** end with newlines because of the split, so `word_new = word.rstrip("\n")` **accomplishes nothing**. You see an extra newline at the end **from the `print` call**. Please see the linked duplicate for working approaches to the problem. – Karl Knechtel Mar 18 '23 at 04:58
  • Please see the linked duplicate for working approaches to the problem - this is assuming that the file already has one word on each line. If you are trying to split up words from a multi-line file, simply call `.split()` instead of `.split('\n')` - if that is the issue I can link a different duplicate for that. – Karl Knechtel Mar 18 '23 at 05:03

0 Answers0