我正在遍历目录以更新某些工作簿中的外部链接,然后将其目的是使csv脱离这些工作簿。我有它的功能,但没有将.csv文件后缀获取名称和路径,而是将.csv添加到.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')
答案 0 :(得分:1)
使用os.path.splitext将名称与扩展名分开:
...
name, ext = os.path.splitext(filename)
mycsv = os.path.join(directory, name + suffix)
...
答案 1 :(得分:0)
由于filename
的末尾包含.xlsx
,因此您将要替换为.csv
而不是附加。
例如,使用filename.replace('.xlsx', '.csv')
代替filename + suffix
答案 2 :(得分:0)
您可以仅对文件名使用分割功能:
Name M/F Grade Size Notes
0 Peter Parker M 1/2 YM Baughman
1 Tony Stark M 1/2 YL Baughman
2 Steve Rogers M 1/2 YM Baughman
3 Donald Blake M 1/2 YM Baughman
4 Bruce Banner M 3/4 YM Baughman