There are no Excel CSV
files. CSV is a flat text file with a specific, minimal format. xlsx
files on the other hand are ZIP packages containing XML files. I suspect what you really ask is how to read a CSV text file saved with one encoding and convert it to XLSX.
The answers to this question show how to do this:
- Load the CSV file using the csv library and then
- Write it out to XLSX using openpyxl
import csv
import openpyxl
wb = openpyxl.Workbook()
ws = wb.active
with open('file.csv') as f:
reader = csv.reader(f)
for row in reader:
ws.append(row)
wb.save('file.xlsx')
The CSV file is read with open
. As the csv
docs warn :
Since open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding()). To decode a file using a different encoding, use the encoding argument of open
You may have to use the utf-8
, utf-8-sig
or utf-16-le
encodings:
with open('file.csv', encoding='utf-8') as f: