分割txt文件,并追加到两个单独的列表的Python [英] Split .txt file and Append to Two Separate Lists Python

查看:662
本文介绍了分割txt文件,并追加到两个单独的列表的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个txt文件,看起来像这样:

I have a .txt file that looks like this:

我怎么会通过文本文件的每一行遍历,对逗号两个字符串元件分开,并且每个字符串元素添加到其自己的名单?

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?

我有:

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?

推荐答案

Usings清单不会让你知道,如果你的文件每行一个以上的逗号,所以我会用元组代替,像这样的:

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

这篇关于分割txt文件,并追加到两个单独的列表的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆