Changeset - afada0171a31
[Not reviewed]
0 1 0
Lance Edgar - 10 years ago 2015-02-07 12:41:15
ledgar@sacfoodcoop.com
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..?
1 file changed with 7 insertions and 5 deletions:
0 comments (0 inline, 0 general)
rattail/files.py
Show inline comments
 
@@ -19,49 +19,51 @@
 
#  You should have received a copy of the GNU Affero General Public License
 
#  along with Rattail.  If not, see <http://www.gnu.org/licenses/>.
 
#
 
################################################################################
 
"""
 
File Utilities
 

	
 
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
 
import lockfile
 
import tempfile
 
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.
 

	
 
    :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
 

	
 

	
 
def creation_time(path):
 
    """
 
    Returns the "naive" (i.e. not timezone-aware) creation timestamp for a
 
    file.
 

	
 
    :param path: Path to the file.
 
    :type path: string
 

	
 
    :returns: The creation timestamp for the file.
0 comments (0 inline, 0 general)