1

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

4 回答 4

2

这并不难:

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

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

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

于 2013-06-06T23:12:32.027 回答
0

通常来说,一般来说:

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

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

于 2013-06-06T23:10:39.320 回答
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])

它不适用于非常大的文件

于 2013-06-06T23:28:38.297 回答
-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
于 2013-06-06T23:10:46.467 回答