2013-04-29 7 views
1

파일에서 특정 줄을 읽으려고하고 각 청크의 프로세스를 끝낸 후 계속 읽으려고합니다. 파일에 19000 줄이 있다고 가정 해 보겠습니다. 매번 처음 19 줄을 추출하고 그 줄로 계산을하고 다른 파일에 출력을 씁니다. 그런 다음 다음 19 줄을 다시 추출하고 동일한 처리를 수행합니다. 그래서 다음과 같은 방법으로 줄을 추출하려고했습니다 :python 파일에서 특정 줄을 읽고 계속하십시오.

n=19 
x = defaultdict(list) 

i=0 

fp = open("file") 
for next_n_lines in izip_longest(*[fp] *n): 
    lines = next_n_lines 

    for i, line in enumerate(lines): 
     do calculation 
    write results 

이 코드는 첫 번째 청크에서 작동합니다. 당신 중 누구도 나를 도울 수 있습니까? 다음 n 개의 덩어리를 계속하려면 어떻게해야합니까? 많은 감사드립니다!

+0

코드는 이미 19 줄로 그룹을 반복합니다. 문제가 무엇입니까? –

+0

@Francis Avila : 내가 직면 한 문제는 다음 덩어리로 이동하는 것입니다. 첫 번째 청크에 대해서만 작동합니다. –

+0

아니요, 모든 청크를 반복합니다. 표시하지 않는 코드에 또 다른 문제가 없다고 확신합니까? 어딘가에서 '쉬는 것'인가? –

답변

3

귀하의 코드는 이미 19 줄로 된 그룹을 추출하므로 귀하의 문제가 무엇인지 잘 모릅니다.

나는 약간 솔루션을 정리할 수 있지만, 코드 같은 일을 수행

from StringIO import StringIO 

class CtxStringIO(StringIO): 
    def __enter__(self): 
     return self 
    def __exit__(self, *args): 
     return False 

infile = CtxStringIO(''.join('{}\n'.format(i) for i in xrange(19*10))) 
outfile = CtxStringIO() 


# this should be the main loop of your program. 
# just replace infile and outfile with real file objects 
with infile as ifp, outfile as ofp: 
    for chunk in grouper(19, ifp, '\n'): 
     ofp.writelines(process_chunk(chunk)) 

# see what was written to the file 
print ofp.getvalue() 

이 : 여기

from itertools import izip_longest 

# grouping recipe from itertools documentation 
def grouper(n, iterable, fillvalue=None): 
    "Collect data into fixed-length chunks or blocks" 
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx 
    args = [iter(iterable)] * n 
    return izip_longest(fillvalue=fillvalue, *args) 

def process_chunk(chunk): 
    "Return sequence of result lines. Chunk must be iterable." 
    for i, line in enumerate(chunk): 
     yield 'file-line {1:03d}; chunk-line {0:02d}\n'.format(i, int(line)) 
    yield '----------------------------\n' 

모든 라인이 방문한 것을 보여줍니다 몇 가지 테스트 코드 테스트 케이스는 다음과 같은 줄을 출력해야합니다 :

file-line 000; chunk-line 00 
file-line 001; chunk-line 01 
file-line 002; chunk-line 02 
file-line 003; chunk-line 03 
file-line 004; chunk-line 04 
... 
file-line 016; chunk-line 16 
file-line 017; chunk-line 17 
file-line 018; chunk-line 18 
---------------------------- 
file-line 019; chunk-line 00 
file-line 020; chunk-line 01 
file-line 021; chunk-line 02 
... 
file-line 186; chunk-line 15 
file-line 187; chunk-line 16 
file-line 188; chunk-line 17 
file-line 189; chunk-line 18 
---------------------------- 
+0

그런 멋진 해결책을 가져 주셔서 감사합니다. –

2

귀하의 질문에 명확하지 않지만, 당신이 계산하는 모든 N 라인 (귀하의 예에서는 19)에 따라 달라집니다.

그래서 그것은 모든 라인을 추출하는 것이 좋습니다 다음 작업을 수행합니다

N = 19 
inFile = open('myFile') 
i = 0 
lines = list() 

for line in inFile: 
    lines.append(line) 
    i += 1 
    if i == N: 
     # Do calculations and save on output file 
     lines = list() 
     i = 0 
+0

감사합니다. 예, 계산은 19 줄 모두에 달려 있습니다. 나는 너의 것을 시도 할 것이다. 다시 한 번 감사드립니다! –

+1

방금 ​​해결책에 오류가있는 것으로 나타났습니다 (파일의 끝 부분을 제대로 검사하지 못했을 수도 있음). 초 단위로 수정합니다. – halflings

+0

이제 작동합니다. – halflings

2

이 솔루션은 메모리에서 모든 행을로드 할 필요가 없다합니다.

n=19 
fp = open("file") 
next_n_lines = [] 
for line in fp: 
    next_n_lines.append(line) 
    if len(next_n_lines) == n: 
     do caculation 
     next_n_lines = [] 
if len(next_n_lines) > 0: 
    do caculation 
write results 
+0

귀하의 제안과 해결책에 감사드립니다! –

+1

@BlueIce 파일의 행 수가 19의 배수가 아닌 경우도 처리 할 수 ​​있습니다. – ArkChar