2016-08-06 19 views
-3

大きなtxtファイルには100万行が含まれていますが、それぞれを10行に分割したいのですが、どのようにpythonを使って行うのですか? は、私はいくつかの関連の質問を発見し、このようなコードを持っている:大きなtxtファイルを小さなtxtファイルに分割する方法

def split_file(filepath, lines=30): 

    """Split a file based on a number of lines.""" 

    path, filename = os.path.split(filepath) 

    # filename.split('.') would not work for filenames with more than one . 

    basename, ext = os.path.splitext(filename) 

    # open input file 

    with open(filepath, 'r') as f_in: 

     try: 
      # open the first output file 
      f_out = open(os.path.join(path, '{}_{}{}'.format(basename, 0, ext)), 'w') 
      # loop over all lines in the input file, and number them 
      for i, line in enumerate(f_in): 
       # every time the current line number can be divided by the 
       # wanted number of lines, close the output file and open a 
       # new one 
       if i % lines == 0: 
        f_out.close() 
        f_out = open(os.path.join(path, '{}_{}{}'.format(basename, i, ext)), 'w') 
       # write the line to the output file 
       f_out.write(line) 
     finally: 
      # close the last output file 
      f_out.close() 

しかし、それだけで小さなtxtファイル内の関数が、私のターゲットファイルでは動作しません、と私はその理由を知らないエラー情報を持っていません。

+3

あなたのためにコードを記述していただきたいようです。多くのユーザーは、苦労しているコーダーのコードを作成したいと考えていますが、通常、ポスターが既に問題を解決しようとしているときにのみ役立ちます。この努力を実証する良い方法は、これまでに書いたコード、サンプル入力(もしあれば)、期待される出力、実際に得られる出力(出力、トレースバックなど)を含めることです。あなたが提供する詳細があれば、受け取る可能性のある回答が増えます。 [FAQ](http://stackoverflow.com/tour)と[How to Ask](http://stackoverflow.com/questions/how-to-ask)を確認してください。 – TigerhawkT3

+1

これまでに何を試しましたか?タスクのどの部分に問題がありますか? – EJoshuaS

+0

私は感謝を更新しました – zjsuper

答えて

0

これは動作するはずです。それはちょっと回り道ですが、人間が読める間にあなたの謎のエラーを回避する必要があります。

まず、2つの便利な機能を定義しましょう。最初のファイルはファイルを読み取り、各行をリスト要素にし、2番目の要素はファイルとしてリストを書き込みます。

注意:2番目の関数は、その名前のファイルが存在しない場合は新しいファイルを作成し、存在する場合はファイルを上書きします。

def line_reader(target_file):  
    with open(target_file, 'r') as file: 
     store = file.readlines() 
     return store 

def line_writer(file_name, store): 
    with open(file_name, 'w') as file: 
     file.writelines(store) 

次に、実際にファイルを小さなファイルに分割する機能を定義しましょう。

def breakdown(target, new_file_name, chunk_length = 10): 
    # First let's store a list representing the data from the original file 
    data = line_reader(target) 

    # part_no is solely for naming purposes 
    part_no = 0 
    # this list will be used to hold smaller chunks of lines 
    tmp_list = [] 
    condition = True 
    while condition: 
     for i in range(chunk_length): 
      # just a basic check to make sure that there are still lines left to be replaced 
      if len(data) > 0: 
       tmp_list.append(data.pop(0)) 
      else: 
       condition = False 
       tmp_list.append('\n') 
       break 

     part_no += 1 
     line_writer(str(new_file_name + ' ' + str(part_no)), tmp_list) 
     tmp_list = [] 

呼び出す内訳は、最後に1つの空白行に続いてchunk_length行(デフォルトでは10)の小さなファイルにターゲットに分割します。最後のファイルは元のファイルから残ったものだけになります。

関連する問題