Reputation: 63
inFile = open("subjects.txt","r")
global subArray
subArray = []
global line
for line in inFile:
subArray.append(line)
inFile.close()
return subArray
This how I get the data when in is in different lines in the text file like
math
science
art
I need to know how to do it when the data is in one line
math , science , geography
Upvotes: 1
Views: 364
Reputation: 7325
line.split(" , ")
will turn the string into an array a list of strings. You might also look at the standard "csv" module.
Upvotes: 4
Reputation: 20992
This will work if the entire file is just one line:
subArray = [subj.strip() for subj in open("subjects.txt","r").read().split(',')]
or if you want to do it in a loop:
inFile = open("subjects.txt","r")
subArray = []
for line in inFile
for subject in line.split(','):
subArray.append(subject.strip())
return subArray
or using the csv module:
import csv
subArray = []
for line in csv.reader(open('subjects.txt', 'rb')):
for subject in line:
subArray.append(subject)
Upvotes: 3