hedge_funder
hedge_funder

Reputation: 7

How would one limit characters per line when printing a raw_input to a text file?

I'm attempting to write a report creating script. Simply put I have the user submit strings via a few raw_input()s. Theses strings are assigned to global variables and when they are finished I need the script to print the string but limit it to only 80chars per line. I've looked at the textwrap module and looked around for anyone else who's asked this. But i've only found people trying to limit the characters being printed within the script from a raw input or from a pre existing file and never trying to print out to a new file. Heres some code that is basically a shorter version of what im trying to do.

Here's the code:

def start():
    global file_name
    file_name = raw_input("\nPlease Specify a filename:\n>>> ")
    print "The filename chosen is: %r" % file_name
    create_report()
    note_type()

def create_report():
    global new_report
    new_report = open(file_name, 'w')
    print "Report created as: %r" % file_name
    new_report.write("Rehearsal Report\n")
    note_type()

def note_type():
    print "\nPlease select which type of note you wish to make."
    print """
1. Type1
2. Print
"""
    answer = raw_input("\n>>> ")
    if answer in "1 1. type1 Type1 TYPE1":
        type1_note()
    elif answer in "2 2. print Print PRINT":
        print_notes()
    else:
        print "Unacceptable Response"
        note_type()

def type1_note():
    print "Please Enter your note:" 
    global t1note_text
    t1note_text = raw_input(">>> ")
    print "\nNote Added."
    note_type()

def print_notes():
    new_report.write("\nType 1: %r" % t1note_text)
    new_report.close
    print "Printed. Goodbye!"
    exit(0)

start()  

And Here is my terminal input

---
new-host-4:ism Bean$ python SO_Question.py  

Please Specify a filename:  
">>> " test3.txt  
The filename chosen is: 'test3.txt'  
Report created as: 'test3.txt'  

Please select which type of note you wish to make.  

1. Type1  
2. Print  


">>> " 1  
Please Enter your note:  
">>> "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam at dignissim diam.        Donec aliquam consectetur pretium. Sed ac sem eu nulla tincidunt accumsan. Praesent vel velit   odio. Donec porta mauris ut eros bibendum consequat. Class aptent taciti sociosqu ad litora  torquent per conubia nostra, per inceptos himenaeos. Integer adipiscing nibh in turpis  placerat non interdum magna convallis. Phasellus porta mauris at nibh laoreet ac vulputate   elit semper.

Note Added.  

Please select which type of note you wish to make.  

1. Type1  
2. Print  


">>> "2  
Printed. Goodbye!  
new-host-4:ism Bean$   

The only problem being that when I open the file (test3.txt) the entire paragraph of lorem ipsum is all printed to one line. Like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam at dignissim diam. Donec aliquam consectetur pretium. Sed ac sem eu nulla tincidunt accumsan. Praesent vel velit odio. Donec porta mauris ut eros bibendum consequat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer adipiscing nibh in turpis placerat non interdum magna convallis. Phasellus porta mauris at nibh laoreet ac vulputate elit semper.

Anybody got any advice to get textwrap to print 80chars per line to the file?

Upvotes: 0

Views: 8786

Answers (3)

Sami N
Sami N

Reputation: 1180

You can try and use the Textwrap module:

from textwrap import TextWrapper

def print_notes(t1note_text):
    wrapper = TextWrapper(width=80)
    splittext = "\n".join(wrapper.wrap(t1note_text))
    new_report.write("\nType 1: %r" % splittext)
    new_report.close
    print "Printed. Goodbye!"
    exit(0)

Upvotes: 0

Olivier Lasne
Olivier Lasne

Reputation: 981

In python 3, you can use textwrap.fill to print 80 characters lines :

import textwrap

print (textwrap.fill(your_text, width=80))

see https://docs.python.org/3.6/library/textwrap.html

Upvotes: 2

dckrooney
dckrooney

Reputation: 3121

If you don't want to use any additional modules, you could split the value of your user input into 80 character chunks yourself:

def split_input(string, chunk_size):
    num_chunks = len(string)/chunk_size
    if (len(string) % chunk_size != 0):
        num_chunks += 1
    output = []
    for i in range(0, num_chunks):
        output.append(string[chunk_size*i:chunk_size*(i+1)])
    return output

Then you could print the output list to a file:

input_chunks = split_input(user_input, 80)
for chunk in input_chunk:
    outFile.write(chunk + "\n")

UPDATE:

This version will respect space-separated words:

def split_input(user_string, chunk_size):
    output = []
    words = user_string.split(" ")
    total_length = 0

    while (total_length < len(user_string) and len(words) > 0):
        line = []
        next_word = words[0]
        line_len = len(next_word) + 1

        while  (line_len < chunk_size) and len(words) > 0:
            words.pop(0)
            line.append(next_word)

            if (len(words) > 0):
                next_word = words[0]
                line_len += len(next_word) + 1

        line = " ".join(line)
        output.append(line)
        total_length += len(line) 

    return output

Upvotes: 3

Related Questions