gpt4 book ai didi

excel - 读取文件并将特定字段输出到 CSV 文件

转载 作者:行者123 更新时间:2023-12-04 22:28:37 25 4
gpt4 key购买 nike

我正在尝试根据关键字搜索数据并将该数据导出到 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 文件。

最佳答案

试试这个 - 我将你的工作簿和工作表定义移到循环之外,所以它不会一直被重新定义。

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"

workbook = xlsxwriter.Workbook(xls_output_path + 'Test.xlsx') #Creates the xls file
worksheet = workbook.add_worksheet()

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.




worksheet.write('A' + excel_inc_str, split_lines[4]) #Write data from
#split_lines[4]
#to column A
workbook.close()

关于excel - 读取文件并将特定字段输出到 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55365818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com