Home > front end >  How to add a two-digit number to the beginning of a file while keeping its name and extension. with
How to add a two-digit number to the beginning of a file while keeping its name and extension. with

Time:02-01

How to add a two-digit number to the beginning of a file while keeping its name and extension.

I need to add a number in the format {t:02} before the file name separating them with a blank space and keeping the same extension. Example: "pink.pdf" -> "01 pink.pdf".

Input directory:

pink.pdf
orange red.png
red green.txt
green yellow.pdf
green pink.pdf
black green.jpg

Output directory:

01 pink.pdf
02 orange red.png
03 green yellow.pdf
04 green pink.pdf

Is it possible to check with a given list if the file to be renamed belongs to it, otherwise skip it and continue with the next file?

Example:

List = ['pink.pdf', 'orange red.png', 'green yellow.pdf', 'green pink.pdf']

Note: I am a novice python user

CodePudding user response:

You can use the os and os.path modules in Python to rename the files
import os

file_list = ['pink.pdf', 'orange red.png', 'green yellow.pdf', 'green pink.pdf']

# Get the current working directory
cwd = os.getcwd()

# Loop through the files in the current directory
for i, filename in enumerate(os.listdir(cwd)):
    if filename in file_list:
        # Get the file name and extension
        base, ext = os.path.splitext(filename)

        # Rename the file with a two-digit number
        os.rename(filename, f"{i 1:02} {base}{ext}")

The os.path.splitext function is used to split the filename into its base name and extension.

CodePudding user response:

The operator also works for strings, so:

longer_names = [str(i)   filename for i,filename in enumerate(filenames)]

You can use f"{i:02}" for the left zero padding.

CodePudding user response:

Here's an answer that uses pathlib, which I prefer to os.path. It also doesn't use enumerate because you only want to increment the prefix when a file in in your list.

from pathlib import Path
# get all files in the current directory
all_files = Path.cwd().glob("*.*")  

renamers = ["pink.pdf", "orange red.png", "green yellow.pdf", "green pink.pdf"]
count = 1
for file_path in all_files:
    if file_path.name in renamers:
        new_name = f"{count:02} {file_path.name}"
        print(f"Renaming {file_path.name} to {new_name}")
        file_path.rename(new_name)
        count  = 1
    else:
        print(f" skipped {file_path.name}")

If you don't want to use the current working directory, change the glob:

all_files = Path.("\path\to\my\files").glob("*.*")  

You can also use the glob to filter by file name, e.g. "*.pdf".

I see the following output:

 skipped black green.jpg
Renaming green pink.pdf to 01 green pink.pdf
Renaming green yellow.pdf to 02 green yellow.pdf
Renaming orange red.png to 03 orange red.png
Renaming pink.pdf to 04 pink.pdf
 skipped red green.txt
  • Related