Reputation: 145
I have written some simple and easy code to rename a lot of files. The source Folder is path (the files are in the main Folder and a lot of sub-Folders. The target Folder is newPath (here I want to assemble all the renamed files together.
The code works, but I want to change / update it.
I dont now how to include the Folder name in the shutil.copy
"changed" + str(count) + ".csv"
How can I get the Name of the Folder, where the file is in, includes in the copied name?
import os
import shutil
def main():
path = "C:/code/convert/renamefiles/source"
newPath = "C:/code/convert/renamefiles/target"
count = 1
for root, dirs, files in os.walk(path):
for i in files:
if i.endswith('lb_panorama.csv'):
shutil.copy(os.path.join(root, i), os.path.join(newPath, "changed" + str(count) + ".csv"))
print i
count += 1
if __name__ == '__main__':
main()
Upvotes: 0
Views: 3237
Reputation: 1675
I used pathlib
to iterate through directories because it's much simpler than the method you were using. I do not check if the source and destination paths exist, so an exception will be thrown if they don't. When files are copied, they are renamed to their source parent folder's name, which is retrieved with pathlib.Path.parent.name
.
The top bit of code is for the logger. It logs to a file named CopyErrors.log
and is created in the same directory as the Python script. To log errors, I just catch any exceptions that shutil.copy
throws.
import pathlib
import shutil
import logging
def main(src, dest):
logger = logging.getLogger("CopyFiles")
logger.setLevel(logging.WARNING)
handler = logging.FileHandler(filename = "CopyErrors.log",
encoding = "utf-8",
mode = "w")
handler.setFormatter(logging.Formatter(
"%(asctime)s - [%(levelname)s] %(name)s: %(message)s"))
logger.addHandler(handler)
pathSrc = pathlib.Path(src).glob("**/*.csv")
for file in pathSrc:
try:
shutil.copy(str(file), f"{dest}/{file.parent.name}.csv")
except Exception as e:
logger.warning(f"{file} could not be copied.\n"
f"{type(e).__name__}: {e}")
if __name__ == '__main__':
main("Z:/Geoportal/MoMa/MoMa1", "Z:/Geoportal/MoMa/Moma1_new")
Upvotes: 2