Search code examples
pythonlistappendtraversal

Split .txt file and Append to Two Separate Lists Python


I have a .txt file that looks like this:

enter image description here

How could I traverse through each line of the text file, split the two string elements on the comma, and append each string element into its own list?

I have:

longSubjectNames = [] #example: "Academy for Classical Acting"
abbreviations = [] #example: "ACA"

with open ("/Users/it/Desktop/Classbook/classAbrevs.txt", "r") as myfile:
subjectAndAbrevs = tuple(open("/Users/it/Desktop/Classbook/classAbrevs.txt", 'r'))

for subAbrevsLine in subjectAndAbrevs:
   subAbrevsLine.strip()
   allSubsAndAbrevs = subAbrevsLine.split(",")

This isn't splitting the string elements correctly. Once the two string elements are split, how could I then append them to their respective lists?


Solution

  • Usings lists will not let you know if your file as more than one comma per a line, so I would use tuples instead, like such:

    longSubjectNames = [] #example: "Academy for Classical Acting"
    abbreviations = [] #example: "ACA"
    
    with open ("/Users/it/Desktop/Classbook/classAbrevs.txt", "r") as myfile:
        lines = myfile.readlines()
        for line in lines:
            name, abrev = line.replace("\n","").split(",")
            longSubjectNames.append(name)
            abbreviations.append(abrev)
    
    print longSubjectNames
    print abbreviations