Skip to content

Commit

Permalink
Merge pull request #244 from jnsebgosselin/makedirs_if_needed_when_sa…
Browse files Browse the repository at this point in the history
…vingfiles

PR: Make save_content_to_file more robust
  • Loading branch information
jnsebgosselin authored Dec 20, 2018
2 parents 5c8399e + 90eb8af commit e5c4e6e
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion gwhat/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def save_content_to_file(fname, fcontent):
Smart function that checks the extension and save the content in the
appropriate file format.
"""
root, ext = os.path.splitext(fname)
root, ext = osp.splitext(fname)
if ext in ['.xlsx', '.xls']:
save_content_to_excel(fname, fcontent)
elif ext == '.tsv':
Expand All @@ -74,13 +74,15 @@ def save_content_to_csv(fname, fcontent, mode='w', delimiter=',',
Save content in a csv file with the specifications provided
in arguments.
"""
create_dirname(fname)
with open(fname, mode, encoding='utf8') as csvfile:
writer = csv.writer(csvfile, delimiter=delimiter, lineterminator='\n')
writer.writerows(fcontent)


def save_content_to_excel(fname, fcontent):
"""Save content in a xls or xlsx file."""
create_dirname(fname)
root, ext = os.path.splitext(fname)
if ext == '.xls':
wb = xlwt.Workbook()
Expand All @@ -96,6 +98,13 @@ def save_content_to_excel(fname, fcontent):
ws.write_row(i, 0, row)


def create_dirname(fname):
"""Create the dirname of a file if it doesn't exists."""
dirname = osp.dirname(fname)
if dirname and not osp.exists(dirname):
os.makedirs(dirname)


def delete_file(filename):
"""Try to delete a file on the disk and return the error if any."""
try:
Expand Down

0 comments on commit e5c4e6e

Please sign in to comment.