【问题标题】:In Python, how do you read specific characters on a specific line在 Python 中,如何读取特定行上的特定字符
【发布时间】:2013-06-03 03:29:51
【问题描述】:

如果我有一个文本文件,我想读取第二行的第 1、2、3、4、5、6、7 和 8 个字符,我会写什么?我对 python 很陌生,正在使用 v3.3

示例文本文件

Hello, my name
is Bob. How are
you?

如何只读取字符 H、E、L、L、(,)、( )、M 和 Y?

【问题讨论】:

  • 这些字符来自 first 行..

标签: python line


【解决方案1】:

不难:

with open('filename.txt', 'r') as handle:
    first_line = handle.readline()

    print(first_line[0], first_line[1], ...)

您应该从阅读 Python 教程开始。

【讨论】:

    【解决方案2】:

    一般来说:

    1. 打开文件
    2. 逐行阅读
    3. 如果您正在阅读的行是第二行,那么:
      1. 逐字符读取行
      2. 如果字符是第 1、第 2、第 3.... 打印。

    这方面的 python 细节非常简单。我建议你看看你能想出什么——这样你会学得更好。

    【讨论】:

      【解决方案3】:

      我会这样做:

      with open('thefile.txt') as thefile:
          lines = thefile.readlines()  # return a list with all the lines of the file
      
      # then to print 4th character of 6th line you do (mind zero-based indexing):
      print(lines[5][3])
      

      它不适用于非常大的文件

      【讨论】:

        【解决方案4】:
        # `f` is your file
        skip = 1 # in this case we want to skip one line to read characters from the second one
        for i in range(skip): # this loop will skip a number of lines
            f.realine()
        line = f.readline() # read the line we were looking for
        chars = list(line[:8]) # getting first eight characters as a list
        

        【讨论】:

          猜你喜欢
          • 2021-03-28
          • 2018-06-26
          • 1970-01-01
          • 2018-12-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-26
          • 1970-01-01
          相关资源
          最近更新 更多