2016-12-29 72 views
-5

我需要打开一个txt文件。 在txt文件,我有在python中打开txt文件

Andrei:Popescu:Bucuresti 
Maria:Popescu:Targu-Mures 
.... 

如何读取文本文件分为三个变量和每行做些什么? 对不起,我的英语。

+5

把它与分隔符'csv文件:https://docs.python.org/3/library/csv.html –

+1

或使用'split'。或者手动定位':'等等等等很多方法。 – usr2564301

+0

而我怎么能把它变成三个变量? –

回答

1

注意,名称由冒号(:)分离,以便在split()添加:分裂并把它们存储在多个变量:在这里`文档:

with open("filename.txt") as f: 
     for line in f : 
      word1,word2,word3 = line.split(":") 

    print(word1) 
    print(word2) 
    print(word3) 
+0

非常感谢 –