Why do I rename the folder the files inside it change?

0

I am using lubuntu 17 and had a folder called images with some files of there were trying to rename these files with this program in python:

import os
import re


def repl(match):
    dic = {"4": "0", "5": "1", "6": "2", "7": "3", "Q": "4",
           "J": "5", "K": "6", "A": "7", "2": "8", "3": "9"}
    print(match.group()[0], dic[match.group()[0]])
    return "{}.".format(dic[match.group()[0]])


for name in os.listdir("pasta"):
    old_file = os.path.join("pasta", name)
    new_file = os.path.join("teste", re.sub(
        r"[A-Z0-9][.]", repl, name))
    os.rename(old_file, new_file)

Now if I rename the test folder for images again the files are changed, see:

for example, 9 turns 3. How do I solve this?

    
asked by anonymous 17.01.2018 / 17:09

1 answer

0

You did not create your renaming function so that it is reversible - it's no surprise that double-clicking the same functionality will not restore the original names.

The use of regular expressions, and subs, is a choice that, while perhaps simpler to implement, undermines the readability of the code. regexps are a sub-language within Python, and the api of the match-type objects you use are not user friendly to a third-party reading that does not have it on the tip of the tongue - so your question has gone unanswered all the time.

But even without accompanying your program step by step, just see that your dictionary turns "4" to "0", but there is no reverse entry to change the "0" back to "4". The "0" is not going to work, this should give a "keyerror" in the dictionary and the program for processing (so the names stay the same, and do not change again to something else).

In short: change your dictionary so that all changes have a symmetrical round and round if you want this to happen - and change the line:

return "{}.".format(dic[match.group()[0]])

To:

value = match.group()[0]
return "{}.".format(dic.get(value, value))

Using the .get method will make the dictionary not give an error when the value does not exist: it returns the second parameter, which is the letter itself (change the print also).

    
18.01.2018 / 14:10