在Python中,如何读取特定行上的特定字符

时间:2013-06-06 23:07:45

标签: python line

如果我有一个文本文件,我想阅读第二行的第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?

4 个答案:

答案 0 :(得分:2)

这并不难:

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

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

您应该首先阅读Python教程。

答案 1 :(得分:0)

一般来说:

  1. 打开文件
  2. 逐行阅读
  3. 如果您正在阅读的行是第二行,那么:
    1. 逐个字符地阅读
    2. 如果角色是第1,第2,第3 ......打印出来。
  4. 这方面的python细节非常简单。我建议你看看你能想出什么 - 你会更好地学习。

答案 2 :(得分:0)

我会这样做:

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])

对于非常大的文件

,它无法正常工作

答案 3 :(得分:-1)

# `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