Python How to Wrap Long Lines in Text file

In this short guide is described how to wrap long lines and sentences with pure Python code. The steps in the code are the follows:

  • read text file line by line
  • wrap/collate the lines/sentences by 3 separators: - , , , .
  • output the wrapped/collated text in new file (or the same)
  • execute shell command with Python (optional)

The final result is shown below - as you can notice from the line numbers - line number 4 contains long text and it's displayed continuously from Sublime Text while after the execution the same text in on 3 lines: 12, 13, 14:

python_online_editor_2020

Step 1. Read text File line by line

The first step read input text file line by line from the user home directory. The interesting point here is reading Lunux home folder sign - ~. In order to work such code you need to use method - os.path.expanduser.:

import os

size = 80
file = 'budo'
folder = os.path.expanduser('~/Documents/Fortunes/')

# Read and store the entire file line by line
with open(f'{folder}{file}.txt') as reader:
    provers = reader.readlines()

Now lines are stored as list and they will be processed in next steps

Step 2. Wrap lines by separators

In this step method is defined which is processing the lines one by one. The line is tested against predifined line of size and wrapped if needed. 3 separators are used in this example:

  • ,
  • .

The optimal wrap position is identified by finding the minimum of the maximum of those 3 points: split_char = min(max(comma, dot), max(comma, space), max(dot, space)) - then the line is split continuously. The text logic is kept by keeping the separator.:

# wrap/collate lines by separators [",", " ", "."]
def collate(text, size):
    new_text = []
    split_char = 1
    while split_char > 0:
        comma = str.find(text, ',', size)
        space = str.find(text, ' ', size)
        dot = str.find(text, '.', size)

        split_char = min(max(comma, dot), max(comma, space), max(dot, space))

        if text[:split_char]:
            new_text.append(text[:split_char])
        text = text[split_char+1:].replace('\n', "")

        # if split_char == size:
        #     break
    return new_text

Step 3. Output wrapped lines in new file

Finally new or the same file is written with the collated information. The lines are append with with new line symbol \n. You can find the this code is using the new f-strings introduced in Python 3.6:

# write collated information to new(same) file
with open(f'{folder}{file}.txt', 'w') as writer:
    for wisdom in provers:
        if len(wisdom) > size:
            collated = collate(wisdom, size)
            for short in collated:
                writer.write(short)
                writer.write('\n')
        else:
            writer.write(wisdom)

Step 4. Executing Shell Commands with Python (optional)

This script is used for generating well looking fortunes files. (More information about Linux Fortunes app here: Random Motivation Quotes with Linux Mint). The final step in preparation of fortune file requires executing of simple shell script: strfile -c % budo.txt budo.txt.dat

The shell command creation and call are fully automated with Python:

import os
myCmd = f'strfile -c % {folder}{file}.txt {folder}{file}.txt.dat'
os.system(myCmd)

The final command will product new .dat file which is required by Fortune program. With this the file wrapping and the .dat file generation is completed.

You can find the full code example here: Python wrap long lines
I plan to start also new sequence of short guides about Python, Pandas, Shell etc. scripting. Star or follow the repository if you want to learn more.

Related Article