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

Asked

Viewed 160 times

0

I’m using Lubuntu 17 and had a folder called images with some files dai was trying to rename these files with this programming 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 to images again the files get mixed up, see: inserir a descrição da imagem aqui inserir a descrição da imagem aqui inserir a descrição da imagem aqui

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

1 answer

0

You haven’t created your rename function so it’s reversible - it’s no surprise that running twice the same functionality won’t restore the original names.

The use of regular expressions, and subs there is a choice that, while perhaps simpler to implement, undermines the readability of the code. regexps are a sub-language within Python, and the "match" object api you use is not user-friendly to a third-party reading that doesn’t have it at the tip of the tongue - so your question went unanswered all this time.

But even without following your program step by step, just see that your dictionary turns "4" into "0", but there is no reverse input to change the "0" back to "4". The "0" does not go to anything, it 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 the changes have a symmetrical back and forth if you want this to happen - and change the line:

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

for:

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

The use of the method .get will make the dictionary not error when the value does not exist: it returns the second parameter, which is the letter itself (change the print as well).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.