2017-07-28 8 views
0

私は1500個ものテキストファイルを持っており、すべてのテキストファイルから5行、たとえば4,5,9,14,32行をコピーしたいと思います。これらのファイルの列は、1,500のテキストファイルのうちの一つ下のExcelシートにある。私は1つのtxtファイルだけを取るが、すべてのデータを行にコピーするコードを見つけました。どんな助けもありがとう。 はここに私のコードです:あなたが最初に現在のフォルダに必要なテキストファイルのすべてを置く必要があるだろう特定の行を複数のテキストファイルからExcelファイルにコピーする

import csv 
import xlwt 

import os 
import sys 

# Look for input file in same location as script file: 
inputfilename = os.path.join(os.path.dirname(sys.argv[0]), 
'C:/path/filename.txt') 
# Strip off the path 
basefilename = os.path.basename(inputfilename) 
# Strip off the extension 
basefilename_noext = os.path.splitext(basefilename)[0] 
# Get the path of the input file as the target output path 
targetoutputpath = os.path.dirname(inputfilename) 
# Generate the output filename 
outputfilename = os.path.join(targetoutputpath, basefilename_noext + '.xls') 

# Create a workbook object 
workbook = xlwt.Workbook() 
# Add a sheet object 
worksheet = workbook.add_sheet(basefilename_noext, cell_overwrite_ok=True) 

# Get a CSV reader object set up for reading the input file with tab 
delimiters 
datareader = csv.reader(open(inputfilename, 'rb'), 
        delimiter='\t', quotechar='"') 

# Process the file and output to Excel sheet 

for rowno, row in enumerate(datareader): 
    for colno, colitem in enumerate(row): 

    worksheet.write(rowno, colno, colitem) 

# Write the output file. 
workbook.save(outputfilename) 

# Open it via the operating system (will only work on Windows) 
# On Linux/Unix you would use subprocess.Popen(['xdg-open', filename]) 
os.startfile(outputfilename) 
+0

興味のある行ごとに列を持ちたいのですが、それらの行を抽出した各ファイルの行を入れたいのですか? 'xlwt'を使う必要がありますか? – albert

答えて

0

glob.glob('*.txt')は、その後、これらのファイル名のリストを取得するために使用することができます。各テキストファイルについて、readlines()を使用してファイルを読み取り、itemgetter()を使用して必要な行を抽出します。各ファイルについて、出力ワークシートに新しい行を作成し、各行を別の列エントリとして書き出します。

import xlwt 
import glob 
import operator 

# Create a workbook object 
wb = xlwt.Workbook() 
# # Add a sheet object 
ws = wb.add_sheet('Sheet1', cell_overwrite_ok=True) 
rowy = 0 

for text_filename in glob.glob('*.txt'): 
    with open(text_filename) as f_input: 
     try: 
      lines = [line.strip() for line in operator.itemgetter(4, 5, 9, 14, 32)(f_input.readlines())] 
     except IndexError as e: 
      print "'{}' is too short".format(text_filename) 
      lines = [] 

    # Output to Excel sheet 
    for colno, colitem in enumerate(lines): 
     ws.write(rowy, colno, colitem) 

    rowy += 1 

# Write the output file. 
wb.save('output.xls') 
関連する問題