拆分.text文件并附加到两个单独的列表Python

时间:2015-01-03 22:06:45

标签: python list append traversal

我有一个.txt文件,如下所示:

enter image description here

如何遍历文本文件的每一行,在逗号上拆分两个字符串元素,并将每个字符串元素附加到自己的列表中?

我有:

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(",")

这不是正确分割字符串元素。一旦两个字符串元素被拆分,我怎么才能将它们附加到各自的列表中?

3 个答案:

答案 0 :(得分:-1)

如果你的文件每行都有一个以上的逗号,那么Usings列表不会让你知道,所以我会改用元组,如:

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

答案 1 :(得分:-1)

试试这个:

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

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

    for line in myfile:
        allSubsAndAbrevs = line.replace(" ", "").replace("\n", "").split(",")
        longSubjectNames.append(allSubsAndAbrevs[0])
        abbreviations.append(allSubsAndAbrevs[1])

答案 2 :(得分:-1)

没有一个答案似乎能按照我的意愿行事。这是我提出的一个有效的解决方案:

import csv 

myfile = open("/Users/it/Desktop/Classbook/classAbrevs.csv", "rU")

lines = [tuple(row) for row in csv.reader(myfile)]

longSubjectNames = [] 
abbreviations = [] 

for item in lines:
    longSubjectNames.append(item[0])
    abbreviations.append(item[1])