【问题标题】:Open txt file in python在python中打开txt文件
【发布时间】:2017-05-13 23:39:59
【问题描述】:

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

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

如何将文本文件读入三个变量并为每一行做一些事情? 对不起我的英语。

【问题讨论】:

  • 将其视为带有分隔符的 csv 文件 : 此处的文档:docs.python.org/3/library/csv.html
  • 或使用split。或者手动定位:...等等等等。很多方法。
  • 我怎样才能把它变成三个变量?

标签: python python-2.7 python-3.x


【解决方案1】:

注意名称是用冒号分隔的(:),所以在split() 中添加: 以拆分它们并将它们存储在多个变量中:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多