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