Чтение файла и вывод определенных полей в файл CSV - PullRequest
1 голос
/ 26 марта 2019

Я пытаюсь найти данные по ключевому слову и экспортировать эти данные в 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. Вот где я застреваю. Скрипт печатает только самый последний элемент в столбце Строка 10. Мне нужна помощь, чтобы выяснить, почему он будет печатать данные правильно, но не будет выводить их в электронную таблицу Excel или даже в текстовый файл.

1 Ответ

2 голосов
/ 26 марта 2019

Попробуйте - я переместил определения вашей рабочей книги и рабочей таблицы за пределы цикла, чтобы они не переопределялись.

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()
...