Greencolor
Greencolor

Reputation: 687

Rename the filename using python

I have folder where I have multiple files. Out of this files I want to rename some of them. For example: PB report December21 North.xlsb, PB report November21 North.xslb and so on. They all have a same start - PB report. I would like to change their name and leave only PB report and Month. For example PB report December.

I have tried this code:

import os

path = r'C://Users//greencolor//Desktop//Autoreport//Load_attachments//'
for filename in os.listdir(path):
    if filename.startswith("PB report"):
     os.rename(filename, filename[:-8])

-8 indicates that I want to split the name from the end on the 8th character

I get this error:

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

Any suggestion?

Upvotes: 0

Views: 3186

Answers (3)

Tomerikoo
Tomerikoo

Reputation: 19395

This is a classic example of how working with os/os.path to manipulate paths is just not convenient. This is why pathlib exists. By treating paths as objects, rather than strings everything becomes more sensible. By using a combination of path.iterdir() and path.rename() you can achieve what you want like:

from pathlib import Path

path = Path(r'your path')
for file in path.iterdir():
    if file.name.startswith("PB report"):
        file.rename(file.with_stem(file.stem[:-8]))

Note that stem means the filename without the extension and that with_stem was added in Python 3.9. So for older versions you can still use with_name:

        file.rename(file.with_name(file.stem[:-8] + file.suffix))

Where suffix is the extension of the file.

Upvotes: 2

Lewis
Lewis

Reputation: 2798

You need the path when renaming file with os.rename:

Replace:

os.rename(filename, filename[:-8])

With:

filename_part, extension = os.path.splitext(filename)
os.rename(path+filename, path+filename_part[:-8]+extension)

Upvotes: 1

It works on my pc
It works on my pc

Reputation: 166

The problem is likely that it cannot find the file because the directory is not specified. You need to add the path to the file name:

import os

path = r'C://Users//greencolor//Desktop//Autoreport//Load_attachments//'
for filename in os.listdir(path):
    if filename.startswith("PB report"):
        os.rename(os.path.join(path, filename), os.path.join(path, filename[:-8]))

Upvotes: 1

Related Questions