Python Forum
filetostr - convert a file to a string in python code
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
filetostr - convert a file to a string in python code
#1
the script/program/command converts a file to a string ready to insert into python code.  it supports specified indentation, maximum code width and an assigned variable name.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
file          filetostr.py
purpose       read a file and convert it to a string in a code snippit output
              to stdout.
email         10054452614123394844460370234029112340408691

The intent is that this command works correctly under both Python 2 and
Python 3.  Currently, not all character codespaces are supported under Python 3.
Please report other failures or code improvement to the author.
"""

__license__ = """
Copyright (C) 2016, by Phil D. Howard - all other rights reserved

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA, OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

The author may be contacted by decoding the number
10054452614123394844460370234029112340408691
"""

from sys import argv, stderr, stdout, version

def help( outfile ):
    """help"""
    print( file=outfile )
    print( 'Usage: filetostr indent file_name [ variable_name [ code_text_width ] ]', file=outfile )
    print( 'Usage: filetostr -h | +h | -help | +help | --help | ++help', file=outfile )
    print( file=outfile )
    print( 'Convert the contents of a file to a Python code snippit, output to stdout,', file=outfile )
    print( 'ready to insert or merge into Python code where it is needed.', file=outfile )
    print( 'Note 1: The code text width accounts for the specified indent.', file=outfile )
    print( 'Note 2: The indent is always space, tabs are not supported.', file=outfile )
    print( 'Note 3: Not all character codespaces are supported under Python 3.', file=outfile )
    print( file=outfile )
    return 1


def main( args ):
    """main"""
    a = args

    opts = True
    if len(a) > 1:
        if a[1] in ('--','++'):
            opts = False
            a = a[0:1] + a[2:]

    if len(a) > 1:
        if opts and a[1].lower() in ('-h','+h','-help','+help','--help','++help'):
            return help( stderr )
        try:
            indent = ' ' * int(a[1])
        except (TypeError,ValueError):
            print( a[0].split('/')[-1] + ': invalid operand', '(indent)', file=stdout )
            return help( stderr )
    else:
        print( a[0].split('/')[-1] + ': missing operand', '(indent)', file=stdout )
        return help( stderr )

    if len(a) > 2:
        print('a =',repr(a),file=stderr)
        fname = a[2]
    else:
        print( a[0].split('/')[-1] + ': missing operand', '(file name)', file=stdout )
        return help( stderr )
    
    if len(a) > 3:
        vname = a[3]
    else:
        vname = 'text'

    if len(a) > 4:
        max_len = int( a[4] )
    else:
        max_len = 80
    front = vname + ' = '
    fcont = ' ' * len( front )

    try:
        with open( fname, 'r' ) as file:
            data = file.read( 0x1000000 )
    except IOError:
        print( 'error opening file', repr(a[1]), file=stderr )
        return 1

    line_num = 0
    back = ',\\'
    while len(data) > 0:
        line_num += 1
        for try_len in range(max_len,0,-1):
            rdata = data[try_len:]
            rlen = len(rdata)
            if rlen == 0:
                back = ''
            line = indent + front + repr(data[:try_len]) + back + ' # ' + repr(line_num)
            if len(line) <= max_len:
                break
        print( line )
        if rlen == 0:
            break
        data = rdata
        front = fcont

    return 0


if __name__ == '__main__':
    try:
        result = main( argv )
    except KeyboardInterrupt:
        result = 99
        print( '' )
    except IOError:
        result = 98
    stdout.flush()
    try:
        exit( int( result ) )
    except ValueError:
        print( str( result ), file=stderr )
        exit( 1 )
    except TypeError:
        if result == None:
            exit( 0 )
        exit( 255 )
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
oops!!! i left in some debugging code, remove line 74

and error messages should go to stderr.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020