在python中打开txt文件

2024-05-14 21:14:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

如何将一个文本文件读入三个变量,并对每一行做些什么? 对不起我的英语。在


Tags: 文件txt文本文件andreimariapopescubucurestimures
1条回答
网友
1楼 · 发布于 2024-05-14 21:14:26

请注意,名称由冒号(:)分隔,因此在split()中添加:来拆分它们并将它们存储在多个变量中:

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

    print(word1)
    print(word2)
    print(word3)

相关问题 更多 >

    热门问题