Skip to content

Instantly share code, notes, and snippets.

@toast254
Last active May 16, 2019 14:11
Show Gist options
  • Save toast254/0714264e83d86c2ce983e3e1e5923110 to your computer and use it in GitHub Desktop.
Save toast254/0714264e83d86c2ce983e3e1e5923110 to your computer and use it in GitHub Desktop.
# -*- coding: UTF-8 -*-
import os
import csv
import logging
logger = logging.getLogger(__name__)
def read_csv(file: str = 'in.csv', skip_title: bool = True):
"""Read data from a file (if the file doesn't exist it'll return an empty list)
:param file: the file to load data from
:param skip_title: is there necessary to load titles ?
:return: data loaded (or an empty list)
"""
if not os.path.isfile(file):
logger.error('[FileNotFoundError] ' + file)
return []
liste = [] # init list
with open(file, mode='r', newline='', encoding='UTF-8') as csvfile:
reader = csv.reader(csvfile, delimiter=';', quotechar='|')
if skip_title:
next(reader, None) # don't read first line, it contains titles !
for row in reader:
liste.append(row) # add data
logger.debug('csv file loaded : ' + file + ' ' + str(liste))
return liste
def write_csv(data: list, file: str = 'out.csv'):
"""Write data into a file (if the file already exist it'll be overwritten)
:param data: data to write into a file
:param file: file to write into
"""
with open(file, mode='w', newline='', encoding='UTF-8') as csvfile:
writer = csv.writer(csvfile, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerows(data)
logger.debug('csv file written : ' + file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment