You got it almost right, if you want to iterate over the lines of the file and then over each character in a line, change your second for
to for ch in line:
.
As kuro mentions in the comments, you are currently printing the read words only when you encounter a space character, not on newlines. The way your print
works right now is printing all read words after each space, so a sample output might look like this:
Lorem
Lorem ipsum
Lorem ipsum dolor
Lorem ipsum dolor sit
Lorem ipsum dolor sit amet,
Lorem ipsum dolor sit amet, consetetur
Lorem ipsum dolor sit amet, consetetur sadipscing
If you only mean to print each new word you encounter, you probably want to reset chars = ''
after printing. To suppress newlines after each word, you can use print(chars, end='')
.
It is also safer to open files inside a with
statement, that way closing the file will be handled for you.
Then your code could look like this:
with open('file analysis.txt', 'r') as file:
chars = ''
for line in file:
for ch in line:
chars = chars + ch
if ch == ' ':
print(chars, end='')
chars = ''
This would give the following output:
Lorem ipsum dolor sit amet, consetetur sadipscing
Notice that you print only on spaces, so when your last word is not followed by a space, it will be read but not printed.