简体   繁体   中英

How to Split data in one column of excel into multiple column using python

Can anyone help me in in my program? I have copied some data from TXT file to XLSX using XLSXwriter library, and that data copied in 1 column. Now I would like split that data into multiple columns using space as a separator. Below is my program. Now please suggest me any path forwad.

with open('filter_pre.txt', 'wt+') as logs_pre:
    logs_pre.write(filter_pre)

with open('filter_pre.txt', 'rt+') as Pre_logs:
    lines = Pre_logs.readlines()
    for line in lines:
        Pre_filter_logs.write(row, col, line.strip())
        row += 1
        if not line:
            break
    filter_logs.close()

Writing an answer for I can't comment;

I think you should split the data before writing to the XLSX. It's much easier. The Office suite is notorious for being hard to interact with in code.

with open("inputs.txt") as f:
    rowcount = 0
    for row in f.readlines():
        row = row.strip() # Clean up each row
        # Reset the column counter for each row. 
        # Remove the line below and see what happens ;) 
        columcount = 0 
        for column in row.split(" "): # Break up a row on each space.
            excelsheet.write(rowcount, columcount, column)
            columcount +=1 
        rowcount += 1

You can add additional function (addRow) to the Worksheet object somewhere in you code.

def addRowToXls(self, data, row = 0):
    for colNum, value in enumerate(data):
            self.write(row, colNum, value)

So you can add rows (no matter how many columns in it) to a worksheet easily, like:

worksheet.addRow(data = ["Column 1 text", "Column 2 text", "And so on..."], row = 3) # add to row 4

So in your case the whole code would be like this I guess

import xlsxwriter


def addRowToXls(self, data, row = 0):
    for colNum, value in enumerate(data):
            self.write(row, colNum, value)

xlsxwriter.worksheet.Worksheet.addRow = addRowToXls

workbook = xlsxwriter.Workbook("new_file.xlsx") # new xlsx file
worksheet = workbook.add_worksheet()
worksheet.addRow(data = ["column 1 header text", "column 2 header text", "and so on..."]) # you can skip this
row_save = 1 # start from 0, if you skip column headers

with open('filter_pre.txt', 'rt+') as Pre_logs: # text file to read from
    lines = Pre_logs.readlines()
    for line in lines:
        worksheet.addRow(data = line.split(" "), row = row_save)  # used space as seperator
        row_save += 1

workbook.close()

Tested. Works as supposed to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM