1
    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
1
  • Name subArray is ambiguous because lists are not called arrays in Python, but lists. array is a class of the module array, to create objects whose elements are homogenous. Commented Feb 25, 2011 at 2:53

2 Answers 2

4

line.split(" , ") will turn the string into an array a list of strings. You might also look at the standard "csv" module.

Sign up to request clarification or add additional context in comments.

2 Comments

No. line.split(" , ") turns the string into a LIST of strings. There are no arrays in Python , apart from the objects of the module array that are special.
@eyquem: Yes, of course you are correct there. I was just using the OP's language. Edited. Thanks!
3

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.