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.
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...
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__":
the_list = read_text('example.txt')
print the_list
This worked for me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.