如果我有一个文本文件,我想阅读第二行的第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?
答案 0 :(得分:2)
这并不难:
with open('filename.txt', 'r') as handle:
first_line = handle.readline()
print(first_line[0], first_line[1], ...)
您应该首先阅读Python教程。
答案 1 :(得分:0)
一般来说:
这方面的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