代码之家  ›  专栏  ›  技术社区  ›  boddhisattva

如何在Python中逐行、逐字符地解析文件?

  •  1
  • boddhisattva  · 技术社区  · 15 年前

    谢谢:)。

    2 回复  |  直到 15 年前
        1
  •  8
  •   AndiDog    15 年前

    您可以简单地在Python中迭代每一行。如果希望Python自动关注Windows/UNIX/Mac行结束,请使用通用行结束模式:

    with open("mytextfile.txt", "rtU") as f:
      for line in f:
        # Now you have one line of text in the variable "line" and can
        # iterate over its characters like so:
        for ch in line:
          ... # do something here
    

    在这个示例代码中,您不必关心自己的EOL/EOF。

    请注意 line 变量包括行尾。如果你不想要它们,你可以用 line = line.rstrip()

        2
  •  1
  •   Johannes Charra    15 年前

    您不必担心行和文件结尾,只要这样做就行了

    file = open('yourfile', 'r')
    for line in file.readlines():
        for c in line:
            # do sth.