Skip to content
Advertisement

Replace character in file name with regex python

My script should replace the “|” character of a file it finds via regex in a directory with an “l”.

The code runs but filenames are not replaced. What is wrong?

JavaScript

Advertisement

Answer

Joshua’s answer and the many comments, especially the suggestions from ekhumoro, already pointed out issues and guided to the solution.

Fixed and improved

Here is my copy-paste ready code, with some highlighting inline comments:

JavaScript

Explanation

  • A simple regex to match a pipe-character is |
  • Note: prepended backslash is required to escape special characters (like | (or), escape, ( and ) grouping etc.)
  • Sometimes it is useful to extract code-blocks to functions (e.g. the def print_list) . These can be easily tested.

Test your replacement

To test your replacement a simple function would help. Then you can test it with a fictive example.

JavaScript

If everything works like expected. Then you add further (critical) steps.

Avoid integrating the I/O layer to early

To elaborate on the important advice from ekhumoro: The os.rename is a file-system operation at I/O layer. It has immediate effect on your system and can not easily be undone.

So it can be regarded as critical. Imagine your renaming does not work as expected. Then all the files can be renamed to a cryptic mess, at worst (harmful like ransomware).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement