2014-10-10 216 views
0

是否可以從某一行開始讀取?在我下面舉的例子,我想讀的,只有從Line04使用起從python中的某一行開始讀取

with open (fileList[0], 'rt') as filehandle: 
    for line in filehandle: 
     print line 

# Output: 
# This is a testing file 
# 
# v 1.05 
# v -2.15 

回答

1

這應該工作:

with open('your_file', 'rt') as filehandle: 
    lines = filehandle.readlines()[4:] 

for line in lines: 
    print line 
    #do something 
1
lineno = 0 
for line in filehandle: 
    lineno = lineno + 1 
    if(lineno > 4): 
     print line 
+0

這似乎並沒有工作 – dissidia 2014-10-10 04:19:32

+0

你是什麼意思?哪部分不工作? – Abbath 2014-10-10 04:30:08

+0

好吧,這很奇怪..它現在工作... – dissidia 2014-10-10 04:54:51

2

您可以直接跳過前四線,採用enumerate算來:

with open(fileList[0], 'rt') as filehandle: 
    for line_num, line in enumerate(filehandle): 
     if line_num < 4: 
      continue 

     print line 
     # and do anything else 
+0

我想這是最好的方法。正在尋找一種方法來使用'seek',但這不會奏效。 – 2014-10-10 04:17:45