Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store words read from a file into a list

Apologies for the basic question but I am very new to this programming language. I found similar questions but I cannot making them work for my specific case.

My aim is to read words from a txt file (with more lines, each word is separated by a space), store them into a list and print the list to check what I am doing.

The following code seems to work in terms of printing the single words, but apparently I am not storing them (or I am not able to access the list).

import os

def main():
    read_text(dir_path)

def read_text(file_name):
    file_data = []
    text_file = open(file_name,"r")

    for word in text_file.read().split():
        print(word)
        file_data.append(word)

    text_file.close()
    return file_data        

if __name__ == "__main__":
    main()

What am I doing wrong? Thanks for any suggestions.

like image 284
Stefano Lombardi Avatar asked Nov 23 '25 07:11

Stefano Lombardi


1 Answers

If you want to store the data list for further use, you need to retrieve the list that the read_text method returns:

def main():
    resultList = read_text(dir_path) # store the list
    # use it...
like image 68
Mohammed Aouf Zouag Avatar answered Nov 24 '25 20:11

Mohammed Aouf Zouag



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!