【发布时间】:2017-07-28 16:35:14
【问题描述】:
我有多达 1500 个文本文件,我想从每个文本文件中复制 5 行,例如第 4、5、9、14 和 32 行。我想将这些文件的列放在 Excel 工作表的下方其他,1500 个文本文件。我想出了一个代码,它只接受一个 txt 文件,但将所有数据复制到行中。任何帮助将不胜感激。 这是我的代码:
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)
【问题讨论】:
-
所以您想为您感兴趣的每一行设置一列,为您从中提取这些行的每个文件设置一行?一定要用
xlwt吗?