0

I have made a little code using pyexcel to convert all files in my folder from csv to xlsx. But I want to export it with the same name (instead of file1.xlsx) as it was for each file in the folder. Can you help please?

from pyexcel.cookbook import merge_all_to_a_book
import pyexcel.ext.xlsx
import glob
import os
os.chdir(“/Users/vanicek/Desktop/csv2xlsx” )

i = 0

for file in glob.glob(“*.csv”):
       while os.path.exists(“file%s.xlsx” % i):
               i+=1
       merge_all_to_a_book(glob.glob(“*.csv”), “file%s.xlsx” % i)

print “Exported.”

1 Answer 1

1
import os
import glob
import csv
from xlsxwriter.workbook import Workbook


for csvfile in glob.glob(os.path.join('.', '*.csv')):

workbook = Workbook(csvfile[:-4] + '.xlsx')
worksheet = workbook.add_worksheet()
with open(csvfile, 'rt', encoding='utf8') 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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank, but it crashes with error in encoding: Traceback (most recent call last): File “csv2xlsx_export.py”, line 11, in <module> with open(csvfile, ‘rt’, encoding=‘utf8’) as f: TypeError: ‘encoding’ is an invalid keyword argument for this function Exception Exception: Exception(‘Exception caught in workbook destructor. Explicit close() may be required for workbook.’,) in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook object at 0x10d9eac90>> ignored

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.