Reputation: 59
So I understand how to manipulate a text file and move data in and out of the program, but I'm trying to take raw data in a text file, and load them into an array that is originally empty, how would I make this approach?
Assume my raw data contains 3 words, I want to place those words into a variable called Array
. The raw data of the text file contains the 3 following words: ' Apple Banana Orange '
. I would like it to load into the array as: Array = ["Apple", "Banana", "Orange"]
. How would you approach this?
with open("C:\\Users\\NameList.txt","r") as f:
Array = []
nameList = f.readlines(Array)
Am aware the code is wrong, but I'm not sure how to fix even after reading so much.
Upvotes: 0
Views: 578
Reputation: 350
This will read all the lines in your file:
with open("C:\\Users\\NameList.txt","r")as f:
lines = f.read().splitlines()
Array = list()
for line in lines:
Array.append(line)
print(Array)
for item in Array:
if 'Apple' == item:
print(item)
Output:
#first loop
['Apple', 'Banana', 'Orange']
#second loop
Apple
Upvotes: 0
Reputation: 2692
If your input test.txt
is like below:
Apple Banana Orange
This is the solution you are looking for.
with open("test.txt","r")as f:
text = f.readlines()
Array = text[0].split()
In case you have more than 1 line, you can use this one:
with open("test.txt","r")as f:
text = f.read().splitlines()
Array = [i.split() for i in text]
Upvotes: 1