-1

I am trying to write a function "decode" which takes key, filename, and indicator parameters. key is to indicates the character that needs to replace in the file. filename indicates the name of the file, and indicator indicates whether to encode or decode. Now with the code, I wrote below, no value was passing into filecontent when it loops the second time. What might be the issue here?

   def decode(key, filename, indicator):
        key = list(key)
        openfile = open(filename,'rt')
        if indicator == 'd':
            if len(key) % 2 > 0:
                return
            else:
                for i in range(0, len(key), 2):
                    key[i] = key[i].lower()
                    key[i+1] = key[i+1].lower()
                    indiOne = key[i+1]
                    indiTwo = key[i]
                    filecontent = openfile.read().replace(indiOne, indiTwo)
                print(filecontent)
        return ''

if __name__ == '__main__':
   print(decode('VFSC', 'decript.txt', 'd'))

here is the content in decript.txt:

I lofe eating cpanish apples.

and it was meant to replace all the F with V and C with S:

I love eating spanish apples.
martineau
  • 119,623
  • 25
  • 170
  • 301
Xuanwen Zhang
  • 45
  • 1
  • 6
  • Why are you using `read` in a loop? Do you know what it does? – Tomerikoo Mar 20 '22 at 15:10
  • Instead of calling `.lower()` on each element every time, wouldn't it be easier to just do `key = list(key.lower())`? – Tomerikoo Mar 20 '22 at 15:13
  • This is an unusual way to test for odd length: `if len(key) % 2 > 0`. You would typically write: `if len(key) % 2 != 0` or simply `if len(key) % 2`. – jarmod Mar 20 '22 at 15:14
  • Here is how to do the replacement better: [How to replace multiple substrings of a string?](https://stackoverflow.com/q/6116978/6045800) – Tomerikoo Mar 20 '22 at 15:17

1 Answers1

2

Place this above the loop: filecontent = openfile.read()

Then modify the line inside the loop to look like this:

filecontent = filecontent.replace(indiOne, indiTwo)

This reads from the file only once, and then modifies the same object. The way it is shown, it's being overwritten every loop.