简体   繁体   English

将特定行从多个文本文件复制到Excel文件

[英]Copy specific lines from multiple text files to an excel file

I have as many as 1500 text files and I want to copy 5 lines from every text file, say line 4,5,9,14 and 32. I want to make columns of these files in an excel sheet one below the other, of the 1500 text files. 我有多达1500个文本文件,我想从每个文本文件中复制5行,例如第4、5、9、14和32行。我想将这些文件的列在excel表格中一个放在另一个的下面1500个文本文件。 I have figured out a code that takes in only one txt file but copies all the data into rows. 我想出了一个仅接收一个txt文件但将所有数据复制到行中的代码。 Any help will be appreciated. 任何帮助将不胜感激。 Here is my code: 这是我的代码:

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)

You would first need to put all of your required text files in the current folder, glob.glob('*.txt') could then be used to get a list of these filenames. 您首先需要将所有需要的文本文件放在当前文件夹中,然后可以使用glob.glob('*.txt')获取这些文件名的列表。 For each text file, read the files in using readlines() and extract the required lines using itemgetter() . 对于每个文本文件,使用readlines()读取文件,并使用itemgetter()提取所需的行。 For each file, create a new row in your output worksheet and write each line as a different column entry. 对于每个文件,在输出工作表中创建一个新行,并将每一行写为不同的列条目。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将数据从多个 excel 文件复制到特定工作表上的现有文件 - Copy Data from multiple excel files to existing file on specific sheet 从多个文本文件中提取特定行 - Extract specific lines from multiple text files 从许多文本文件中复制选择的行并粘贴到新文件中 - Copy select lines from many text files and paste to new file 如何从多个 zip 文件夹中的文本文件复制特定行? - how to copy specific line from text files in multiple zip folders? 使用python从多个文本文件中提取特定数据到excel文件 - Extracting specific data from multiple text files to excel file using python 正则表达式使用python从文件中过滤和删除特定的多行文本 - Regex to filter and remove specific multiple lines of text from a file with python 如何在python中复制文件中的特定行 - How to copy the specific lines from file in python Python: How to copy Excel worksheet from multiple Excel files to one Excel file that contains all the worksheets from other Excel files - Python: How to copy Excel worksheet from multiple Excel files to one Excel file that contains all the worksheets from other Excel files 将文本从网站复制到text / excel文件 - Copy text from website to text/excel file 将特定行从多个文件复制到单个文件的代码(并删除部分复制的行) - Code for coyping specific lines from multiple files to a single file (and removing part of the copied lines)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM