Tagged: CSV

Write to CSV File

Writes a line of CSV to a file If the file specified does not already exists, it will be created Otherwise the file will be appended to include the new line Accepts a path to a CSV file, and a CSV line data. def updateCSV(aFilePath, lineData): aFolder, aFile = os.path.split(aFilePath) if os.path.exists(aFilePath): with open(aFilePath, “a+”, newline=”) as csvfile: fieldnames = lineData.keys() writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writerow(lineData) else: if not os.path.exists(aFolder): os.makedirs(aFolder) with open(aFilePath, “x”, newline=”) as csvfile: fieldnames = lineData.keys() writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader()

XLSX to CSV

A simple script to create CSV versions of any XLSX files in a given folder. #The Basics import xlrd import csv import os import re # Create empty variables and hash tables we’ll need later Location = {} # Location to output CSV file when all is done Location[‘input’] = input(‘Folder: ‘) Location[‘output’] = os.path.join(Location[‘input’],’csv’) def csv_from_excel(file): print(“Parsing “, file) wb = xlrd.open_workbook(file) for sheet in wb.sheet_names(): print(‘Exporting Sheet:’, sheet) sh = wb.sheet_by_name(sheet) fileout = os.path.splitext(file)[0] + ” ” + sheet + “.csv” with open(fileout, “w”, newline=””) as csvfile: wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL) for rownum in range(sh.nrows): wr.writerow(sh.row_values(rownum)) csvfile.close() # […]