Matt
Matt

Reputation: 37

Insert blank spaces in txt file - Python

I have a txt file with thousand of rows. Almost all of the rows have the same length of 180 characters but some of the rows are shorter than 180.
I need to add blank spaces to these shorter rows in order to make all of the rows in the text file of the same 180 characters length

filename = "text.txt"
numLines = 0

with open(filename, 'r+') as file:
    for line in file:
        if len(line) != 180:
            emptySpaces = (180 - len(line))

        numLines += 1

I tried to use the insert method but without success. How can I achieve this?

Upvotes: 0

Views: 1128

Answers (1)

vvvvv
vvvvv

Reputation: 31760

You could do it like this:

import fileinput

filename = "text.txt"

for line in fileinput.input(filename, inplace=True):
    line = line.strip("\n")
    if len(line) != 180:
        emptySpaces = " " * (180 - len(line))
    else:
        emptySpaces = ""

    print("{}{}".format(line, emptySpaces), end="\n")

This replaces every line in the file by the new line "{}{}".format(line, emptySpaces).

Upvotes: 1

Related Questions