【发布时间】:2019-08-17 08:21:20
【问题描述】:
我正在尝试根据关键字搜索数据并将该数据导出到 Excel 或文本文件。
当我“打印”变量/列表时,它没有问题。当我尝试将数据输出到文件时,它只输出最后一个条目。我认为迭代有问题,但我无法弄清楚。
import xlsxwriter
#Paths
xls_output_path = 'C:\\Data\\'
config = 'C:\\Configs\\filename.txt'
excel_inc = 0 #used to increment the excel columns so not everything
#is written in "A1"
lines = open(config,"r").read().splitlines()
search_term = "ACL"
for i, line in enumerate(lines):
if search_term in line:
split_lines = line.split(' ') #Split lines via a space.
linebefore = lines[i - 1] #Print the line before the search term
linebefore_split = linebefore.split(' ') #Split the line before via
#space
from_obj = linebefore_split[2] #[2] holds the data I need
to_object = split_lines[4] #[4] holds the data I need
print(len(split_lines)) #Prints each found line with no
#problem.
excel_inc = excel_inc + 1 #Increments for column A so not all of
#the data is placed in A1
excel_inc_str = str(excel_inc) #Change type to string so it can
#concatenate.
workbook = xlsxwriter.Workbook(xls_output_path + 'Test.xlsx') #Creates the xls file
worksheet = workbook.add_worksheet()
worksheet.write('A' + excel_inc_str, split_lines[4]) #Write data from
#split_lines[4]
#to column A
workbook.close()
我创建了这个脚本,所以它会在“config”文件中找到关键字“ACL”的所有行。 然后它能够打印之前的行和找到数据的实际行。这很好用。 我的下一步是将数据输出到 Excel 电子表格。这就是我卡住的地方。 该脚本仅打印 A 列第 10 行中的最后一项。 我需要帮助弄清楚为什么它会正确打印数据,但它不会将其输出到 excel 电子表格甚至 .txt 文件中。
【问题讨论】:
标签: excel python-3.x output