How to Reformat a Text File in Python

The input file and the desired output

The task is to reformat the following input format.

Computing
“I do not fear computers. I fear lack of them.”
— Isaac Asimov

“A computer once beat me at chess, but it was no match for me at kick boxing.”
— Emo Philips

“Computer Science is no more about computers than astronomy is about telescopes.”
— Edsger W. Dijkstra

To the following output format.

“I do not fear computers. I fear lack of them.” (Isaac Asimov)
“A computer once beat me at chess, but it was no match for me at kick boxing.” (Emo Philips)
“Computer Science is no more about computers than astronomy is about telescopes.” (Edsger W. Dijkstra)

The Python code doing the job

The following simple code could do the reformatting in less than a second for a file that contained multiple hundreds quotes.

file = open("input")
content = file.readlines()
file.close()

lines = []
next_line = ""
for line in content:
    line = line.strip()
    if len(line) > 0 and len(line.split()) > 1:
        if line[0] == '“':
            next_line = line
        elif line[0] == '—':
            next_line += " (" + line[2:] + ")"
            lines.append(next_line)
            next_line = ""


file = open("output", "w")
for line in lines:
    file.write(line + "\n")
file.close()

Leave a Reply