I'm trying a way to read a .txt file inside a function. My problem is that it seems you can't use a for loop inside a function because of the return value and the only way I could think of is while loop but I'm having a problem understanding it.
Inside of my .txt contains a sentences that looks like this
#.txt file
This is a sample sentence .
This is a another sample sentence .
I have tried list comprehension but it stores it inside a list. It's easy to read the .txt using for loop but I want to practice using function. This is my progress so far
def read():
return open ('test.txt','r').read();
def sentence()
while True:
The output that i want is:
This
is
a
sample
sentence
.
This
is
a
another
sample
sentence
.
Try this:
Use join to add the newlines and split to add those newlines to each word
def words_in_file(file):
with open(file,'r') as f:
return f.read().split()
words = words_in_file('test.txt')
print(words)
This prints:
This
is
a
sample
sentence
.
This
is
a
another
sample
sentence
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With