0

I am looping through a directory to update the external links in some workbooks and then its the goal to make csv's out of these. I have it functioning but instead of getting the name and path with .csv file suffix it just adds .csv to .xlsx

import os
import csv
import xlrd
import win32com.client

directory = (r'D:\\Dropbox (DBM Vircon)\\XX_Share Internal\\190826 - CD Refresh and Output CSVs')
suffix = '.csv'

for file in os.listdir(directory):
    filename = os.fsdecode(file)
    if filename.endswith(".xlsx"):

        wb = os.path.join(directory, filename)
        print (wb)
        clean = os.path.splitext(wb)
        xlapp = win32com.client.DispatchEx("Excel.Application")
        wb1 = xlapp.workbooks.open(wb)
        xlapp.Visible = False
        wb1.RefreshAll()
        print("refreshed")
        wb1.Save()
        xlapp.Quit()
        print("finished")


        wb1 = xlrd.open_workbook(wb)
        sh = wb1.sheet_by_index(0)
#Below just adds .csv to filename instead of getting name, then adding it 
        mycsv = os.path.join(directory, filename + suffix)
        mynewcsv = open(mycsv, 'w', newline='')
        wr = csv.writer(mynewcsv, quoting=csv.QUOTE_ALL)
        for rownum in range(sh.nrows):
            wr.writerow(sh.row_values(rownum))

        #mycsv.close()

        continue
    else:
        continue

file_obj = open("CSVUpdatecomplete.csv", 'w')

3 Answers 3

1

Separate the name from the extension with os.path.splitext:

...
name, ext = os.path.splitext(filename)
mycsv = os.path.join(directory, name + suffix)
...
Sign up to request clarification or add additional context in comments.

Comments

0

Since filename includes .xlsx at the end, you will want to replace that with .csv rather than append.

For instance, use filename.replace('.xlsx', '.csv') instead of filename + suffix

Comments

0

You can just use split function on filename:

mycsv = os.path.join(directory, filename.split(".")[0] + suffix)

Comments

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.