2017-10-23 15 views
0

に読んでいたもの書き:空行までのファイルを読み込み、新しいテキストファイルabc.txtファイルは次のようになります

product/productId: B000179R3I 
product/title: Amazon.com: Austin Reed Dartmouth Jacket In Basics, Misses: Clothing 
product/price: unknown 
review/userId: A3Q0VJTUO4EZ56 

product/productId: B000GKXY34 
product/title: Nun Chuck, Novelty Nun Toss Toy 
product/price: 17.99 
review/userId: ADX8VLDUOL7BG 

product/productId: B000GKXY34 
product/title: Nun Chuck, Novelty Nun Toss Toy 
product/price: 17.99 
review/userId: A3NM6P6BIWTIAE 

Iは、上記(注するための3つのテキストファイルを作成する必要があります。私が持っています例えばここでは非常に大きくなっています。私は3つを示しています)。

import os 
filepath=os.path.normpath('C:\\Users\\abc.txt') 
with open(filepath,'r') as rf: 
    for index,line in enumerate(rf): 
     with open ('filename{}.txt'.format(index),'w') as output: 
      while(line!=""): 
       output.write(line) 
+0

の場合、ドキュメント内のすべての行に対してアクションを実行する方法があります。それを見つけ、各行ごとに新しい文書を作成し、それを書いてください。 –

+0

https://stackoverflow.com/help/how-to-ask –

答えて

0

while(line!="\n"):

import os 
filepath=os.path.normpath('C:\\Users\\abc.txt') 
with open(filepath,'r') as rf: 
    record = 1 
    output = open('filename{}.txt'.format(record), 'w') 
    for line in rf: 
     if line == "\n": 
      record += 1 
      output.close() 
      output = open('filename{}.txt'.format(record), 'w') 
     else: 
      output.write(line) 

それとも単純にwhile(line!=""):を交換してみてください:

awk -v RS= '{print > ("filename" NR ".txt")}' abc.txt 
0

最適化された方法:

import os 

def get_file(idx): 
    ''' Opens file in write mode using `idx` arg as filename suffix. 
     Returns the file object created 
    ''' 
    fn = 'filename{}.txt'.format(idx) 
    return open(fn, 'w')  

with open(os.path.normpath('C:\\Users\\abc.txt'), 'r') as f: 
    idx = 1 
    out_file = get_file(idx) 
    for l in f: 
     if not l.strip(): 
      out_file.close() 
      idx += 1 
      out_file = get_file(idx) 
     else: 
      out_file.write(l) 
関連する問題