Python Challenge
Write a File
You will be provided a file path for input I, a file path for output O, a string S, and a string T.
Read the contents of I, replacing each occurrence of S with Tand write the resulting information to file O.
You should replace O if it already exists.
Expected output:
Expected output: This Ni is no more. It has ceased to be lis xpircd d go to xi its maker This is a late Ni Its a stiff. Bereft of life, it rests in peace. If you hadnt nailed it to the perch, it would be pushing up the daisies Its rung down the curtain and joined the choir invisible. This is an ex-Ni
# Get the filepath from the command line
import sys
I= sys.argv[1]
O= sys.argv[2]
S= sys.argv[3]
T= sys.argv[4]
# Your code goes here

Respuesta :

Answer:

Hi Brysonbegay! To answer this question, you need to use the file system function provided in the python api and along with the replace feature to replace the word. Please refer to the details below.

Explanation:

The easiest implementation for this question is to utilize the file system api in Python to open the input file I for reading, open the output file O for writing, hen loop through each line in input file and write to output file with string S substituted with replacement string T.  The "open(O, 'w')" command ensures that the output file is overwritten if it already exists. Completed code below.

import sys;

I = sys.argv[1];

O = sys.argv[2];

S = sys.argv[3];

T = sys.argv[4];

# open input file for reading

f = open(I, 'r')  

# open output file for writing

of = open(O, 'w')  

#loop through each line in input file and write to output file with S substituted with T

for line in f:  

 of.write(line.replace(S, T))