-2

I am trying to remove all the hyphen from 50 file names and replace it with a space. I am sure my code is correct, but I am getting an error, I am not sure why it is happening, read many documentation and watch several instruction video, and still no luck. I would also prefer a regex method if possible.

        for f in os.listdir(dstPath):
            r = f.replace("-", "")
            if (r != f):
                os.rename(f, r)

And it gives the error below. My destination of the file path is saved inside a variable named "dstPath"

FileNotFoundError: [WinError 2] The system cannot find the file specified:

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Smit Shah
  • 13
  • 5
  • 2
    You're likely not in the same path as the source file - i.e. `f` should contain the `dstPath` or merged later on e.g. `fpath = os.path.join(dstPath, f)`. Also, your code is not replacing '-' with spaces, it's removing it entirely – jrd1 Jun 02 '22 at 15:29
  • I tried that, I am not sure why I am not in the same path as the source file, as dstPath has the correct path and has been executing well for the other parts of my program. It is not working when I am trying to rename the file. – Smit Shah Jun 02 '22 at 15:36
  • 1
    Please share the output of: `print(dstPath)` (add above for-loop) and `print(f)` (add on the first line within the for-loop - i.e. before the first line with `r`). Only the first two output lines are needed – jrd1 Jun 02 '22 at 15:39

2 Answers2

0

@Smit Sha This looks like a simple case where your code is not able to find the file. Please check the path of the file. P.S. Try not to use the hardcoded path, will vary from system to system.

Ankit
  • 21
  • 1
-1
for srcFilename in os.listdir(srcPath):    
    var1 = os.path.join(dstPath, srcFilename)
    var1= var1.replace("-","")
Smit Shah
  • 13
  • 5
  • 3
    It's a good practice to explain how your 'code' solves the issue. This helps both the original author and everyone in the community who reads your answer afterwards. Posting code w/o explanation as to why it solves the issue is of little help. – blurfus Jun 02 '22 at 19:06
  • 3
    Feel free to [edit] your answer to add the missing information – blurfus Jun 02 '22 at 19:30