如果我有一个文本文件,我想读取第二行的第 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?
这并不难:
with open('filename.txt', 'r') as handle:
first_line = handle.readline()
print(first_line[0], first_line[1], ...)
您应该从阅读 Python 教程开始。
通常来说,一般来说:
这方面的 python 细节非常简单。我建议你看看你能想出什么——那样你会学得更好。
我会这样做:
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])
它不适用于非常大的文件
# `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