From afada0171a31556707f45a2ca6cccaacc3147073 2015-02-07 12:41:15 From: Lance Edgar Date: 2015-02-07 12:41:15 Subject: [PATCH] Add encoding support to `files.count_lines()`. This seemed to be necessary when working with a file with 'latin_1' encoding. Hopefully this is a good change and doesn't break anything..? --- diff --git a/rattail/files.py b/rattail/files.py index 7766cdec247e3695047d91905b8696f82f3a34ec..e212618c6d90f9549951dd0e104336e5b9d4aa6a 100644 --- a/rattail/files.py +++ b/rattail/files.py @@ -28,6 +28,7 @@ This module contains various utility functions for use with the filesystem. from __future__ import unicode_literals +import io import os import os.path import shutil @@ -38,7 +39,7 @@ from datetime import datetime import pkg_resources -def count_lines(path): +def count_lines(path, encoding=None): """ Counts the number of lines in a text file. Some attempt is made to ensure cross-platform compatibility. @@ -46,13 +47,14 @@ def count_lines(path): :param path: Path to the file. :type path: string + :param encoding: Optional encoding to be used when opening the file for + reading. This is passed directly to :func:`python:io.open()`. + :returns: Number of lines in the file. :rtype: integer """ - - f = open(path, 'rb') - lines = f.read().count('\n') + 1 - f.close() + with io.open(path, 'rt', encoding=encoding) as f: + lines = f.read().count('\n') return lines