在python中拆分字符串。许多文字行

时间:2013-11-13 06:46:39

标签: python

文字档案:

  

测试1,15.05.13

的Python:

with open("text_file.txt") as inputFile:
    lines = [line for line in inputFile]
    var1, var2 = lines[0].strip().split(",")

如果我有一行,这项工作很好。如果我有很多行,我怎么能这样做呢?

文字档案:

Test 1,15.05.13
Test 4,15.06.13
Test 5,15.07.13
Test 6,15.08.13

3 个答案:

答案 0 :(得分:1)

使用for循环。这将从文件中一次返回一行(无需将所有行存储在内存中),您可以在其上应用stripsplit

with open("text_file.txt") as inputFile:
    for line in inputFile:
       var1, var2 = line.strip().split(",")

答案 1 :(得分:0)

您可以使用for循环遍历lines

with open("text_file.txt") as inputFile:
    lines = [line for line in inputFile]
    for line in lines:
        var1, var2 = line.strip().split(",")

答案 2 :(得分:0)

您可以将结果放入列表中,如下所示:

with open("text_file.txt") as inputFile:
    vars = [line.strip().split(",") for line in inputfile]

结果:

>>> vars
[['Test 1', '15.05.13'], ['Test 4', '15.06.13'], ['Test 5', '15.07.13'], 
['Test 6', '15.08.13']]