2011-08-05 4 views
2

나는 어떻게 파일을 가지고 분할 표시기로 키워드를 사용하여 하위 파일로 나누는 지 알아 내려고하고있다.파일을 파이썬에서 키워드가있는 파일로 분할 하시겠습니까?

Racecar
line2...
line3...
Racecar
line5...
line6...
line7...
line8...
Racecar
,932 : 필자의 경우는 다음과 같습니다 큰 파일을 10

단어가 나타날 때마다 Racecar 나는 파일을 분할하고 서브 파일을 만들고 싶습니다. 위 예제를 사용하면 File_1은 3 줄을, File_2는 5 줄을, File_3은 2 줄을 갖게됩니다. 이 파일은 다음과 같이 보일 것이다 :

File_1을 :
Racecar
line2...
line3...

File_2을 :
Racecar
line5...
line6...
line7...
(210)

File_3 :
Racecar
line10...

내가 뭔가를 실현 나오지 또는 AWK이 더 적합 할 것입니다,하지만 난 파이썬에서이 작업을 수행해야합니다. 나는 웬일인지 이것을 붙잡고있다.

with open("bigfile", mode="r") as bigfile: 
    reader = bigfile.readlines() 
    for i,line in enumerate(reader): 
     if line.startswith("Racecar"): 
      header = line 
      header_num = i 

가 나는 레이싱 카의 다음 발생을 얻을 수있는 방법을 찾을 수 없기 때문에 갇히지 것 같다 : I는 다음과 같이 작성했습니다. 나는 계속 next() 함수를 사용하고 싶지만, 이것은 분명히 문자열에서 작동하지 않습니다. 사용중인 파일은 메모리에 읽을 수있을 정도로 작습니다. 아무도 이것으로 나를 도울 수 있습니까? 미리 감사드립니다.

+0

QNX에서는 Python이 필요하지 않습니다.). [정규식/패턴이 발견되면 QNX의 분할로 파일을 분할 할 수 있습니다] (http://www.qnx.com/developers/docs/6.5.0/topic/com.qnx.doc.neutrino_utilities/s/split.html). – user712092

답변

3
with open("bigfile", mode="r") as bigfile: 
    reader = bigfile.read() 
    for i,part in enumerate(reader.split("Racecar")): 
     with open("File_" + i+1, mode="w") as newfile: 
      newfile.write("Racecar"+part) 
+0

'readlines'은리스트를 반환하고, 존재하지 않는 split을 호출합니다. –

+0

@Chris 맞아요, 제 답변을 업데이트했습니다. – Vader

+0

@Vader, 선 목록을 읽은 다음 가입하면 낭비가됩니다. 어쨌든'bigfile.read()'에 대해서? – senderle

0
out_array = [] 
with open("bigfile", mode="r") as bigfile: 
    for line in bigfile: 
     if line.startswith("Racecar"): 
      out_array.append(line) 
     else: 
      out_array[-1] += line 

for i in range(len(out_array)): 
    out_filename = "File%d.txt" % i 
    with open(out_filename, mode="w") as out_file: 
     out_file.write(out_array[i]); 

특히 두 개의 루프를 피하는 더 효율적인 방법이 있습니다. 그러나 그것이 당신이 주장하는만큼 작 으면 그것은 중요하지 않아야합니다.

0

당신은 Racecar의 다음 번 등장작을 찾은 것처럼 보입니다. 귀하의 for 루프는 결국 모두에 도달합니다. 문제는 당신이 그들에게 다가 갔을 때해야할 일입니다. 난 당신이 등, header, header_num로가는거야 할 수있는 것은 당신이 할로 (중복 readlines없이하지만) TEST_TBS는 빅에 라인을 반복하는 것입니다 같은

는 것, 그리고 때마다 이해하지 않는다 Racecar 라인을 누르고 새로운 출력 파일을 엽니 다.

으로 지역 :

with open("bigfile", mode="r") as bigfile: 
    smallfile_prefix = "File_" 
    file_count = 0 
    smallfile = open(smallfile_prefix + str(file_count), 'w') 
    for line in bigfile: 
     if line.startswith("Racecar"): 
      smallfile.close() 
      file_count += 1 
      smallfile = open(smallfile_prefix + str(file_count), 'w') 
     else: 
      smallfile.write(line) 
    smallfile.close() 

이 작업을 수행 할 수있는 다른 방법이 있습니다 - Vader's answer에 약간의 변화는 예를 들어, 아마도 더 나은 - 그러나 이것은 원래의 접근 방식에 가장 가까운 것 같다.

관련 문제