Python script that surrounds each line in file with apostrophe

I am trying to run a Python script that takes an input file, manipulate it's content and writes the result to an output file.

I want to surround every line with quotes. Currently I created the script below.

import sys
import re

inFile = sys.argv[1]
outFile = sys.argv[2]

with open(inFile,'r') as i:
    lines = i.readlines()

def manipulate_data(lines):
    content = [x.rstrip('\n') for x in lines]

    res = [re.sub(r"(.+)", r"'\g<0>',", y) for y in content]
    return res

processedLines = manipulate_data(lines)

with open(outFile,'w') as o:
    for line in processedLines:

I run it with python3 input.txt output.txt

It runs, but I wish to change this so that it writes to the output file line by line. I also feel like I am unnecessarily using [do_something for something in somethings] twice.

How can I achieve my desired result?

2 answers

  • answered 2018-10-09 16:35 Austin

    You could read lines from one file, modify and write to another file, all in one go:

    with open(inFile, 'r') as inf, open(outFile, 'w') as outf:
        for line in inf:

  • answered 2018-10-09 17:23 Keerthana Prabhakaran

    You can simply do string formatting while reading the file and write the updated string to the outfile!

    with open(inFile,'r') as f, open(outFile,'w') as w:
        for line in f.readlines():
            w.write("'%s'\n" % line.rstrip('\n'))