Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading all words inside a text file using a function

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
.
like image 315
Jek Avatar asked May 11 '26 06:05

Jek


1 Answers

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
.
like image 54
Jabby Avatar answered May 13 '26 19:05

Jabby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!