0

I'm trying to rename a number of csv files I have nested in multiple subfolders with the name of an upper folder as a prefix e.g.

Ex. go from this:

Folder1
    Apples
        Apples2
            Filename1.csv
    Oranges
        Oranges2
            Filenameb.csv
Folder2
    Blueberry
        Blueberry2
            Filename2.csv
    Oranges
        Oranges2
            Filenamec.csv

To this:
Folder1
    Apples
        Apples2
            Folder1_Filename1.csv
    Oranges
        Oranges2
            Folder1_Filenameb.csv
Folder2
    Blueberry
        Blueberry2
            Folder2_Filename2.csv
    Oranges
        Oranges2
            Folder2_Filenamec.csv

Folder1 and Folder 2 both are subfolders to another larger folder as well.

I have code that basically works, but it breaks after successfully naming ~5 files. It renames all appropriately in one folder and gets through about half of another folder before I get a FileNotFoundError.

My code (barely modified from an answer to this question How to append the grand-parent folder name to the filename?)

import os.path
from pathlib import PurePath
pathway= r”path_to_directory”


for root,dirs,files  in os.walk(pathway)
    try:
        addition = PurePath(root).parts[-3]
        for file in files:
            if file.endswith(".csv"):
                newname =addition + '_' +  file
                #print(newname, os.path.join(root,newname))
                print(newname)
                os.rename(os.path.join(root,file),os.path.join(root,newname))
    except IndexError:
        pass

The error occurs on the os.rename function.

"FileNotFoundError Traceback (most recent call last)"

and

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

It's unclear to me what's wrong, as I've seen os.rename used this way in other posts

KC7777
  • 1
  • 1
  • Your code works just fine for me, so check that your `pathway` is correct. – picobit Apr 11 '23 at 14:02
  • It works until it suddenly breaks, so I'm reasonably confident it isn't the pathway? – KC7777 Apr 11 '23 at 19:23
  • I just ran it on 8,000 files without issue, so I can't help unless you find a way to reproduce the error. – picobit Apr 11 '23 at 20:09
  • Here are some methods for [debugging python scripts](https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues). I'd start by catching `FileNotFoundError` and setting a breakpoint there. That will let you inspect the environment at the time of failure. The next step would be to turn on logging. – picobit Apr 11 '23 at 20:17
  • Figured it out--I probably should have put the actual pathway I was using. I was treating my pathway as a raw string--when I used the double backslash format instead of the r"path" it worked perfectly. – KC7777 Apr 11 '23 at 20:55

0 Answers0