Pergunta

Trying to convert a csv into an xlsx for later manipulation. But no matter what I do its always blank(creates xlsx and adds sheet name fine, no data ever appears though)

Really confused, tried all sorts. The below is the most full piece of code I have used.

import csv
from xlsxwriter.workbook import Workbook

workbook = Workbook("test.xlsx")
worksheet = workbook.add_worksheet("Raw_Data")

with open("C:\Console2\\csv.test",'r') as f:
    reader = csv.reader(f)
    for r, row in enumerate(reader):
        for c, col in enumerate(row):
            worksheet.write(r, c, col)

I do not understand fully the bit after reader line, but it seems all related code I find uses this, I have tried "for statement" for writing a normal csv and that did not work either.

EDIT - issue seems to be with the reader variable, not sure why as its worked on other code fine.

Update - looks like the code overwrites the original csv, dont know why exactly, i just want to read the file and keep contents.

Foi útil?

Solução

You have to close workbook to make it work:

import csv
from xlsxwriter.workbook import Workbook

workbook = Workbook("test.xlsx")
worksheet = workbook.add_worksheet("Raw_Data")

with open("C:\Console2\\csv.test",'r') as f:
    reader = csv.reader(f)
    for r, row in enumerate(reader):
        for c, col in enumerate(row):
            worksheet.write(r, c, col)

workbook.close()

See here for an example.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top