Search code examples
pythonfile-rename

Renaming the beginning of a file name in Python


I am attempting to create an executable that renames all files in its folder.

I am lost on how to reference (and add to) the beginning of a file name.

For example:

file_text.xlsx

What I need it to look like:

10-30-2021_file_text.xlsx

I would like to append to the beginning of the file name, and add my own string(s)

NOTE: 'file_text' are randomly generated file names, and all unique. So I would need to keep the unique names and just add to the beginning of each unique file name.

Here is what I have so far to rename the other files, I figured I could reference a space but this did not work as there are no spaces.

import os

directory = os.getcwd()

txt_replaced = ' '
txt_needed = '2021-10-31'

for f in os.listdir(directory):
    os.rename(os.path.join(directory, f),
                os.path.join(directory, f.replace(txt_needed, txt_replaced)))

I also am curious if there is a way to reference specific positions within the file name.

For example:

text_text1.csv

If there is a way to uppercase only 'text1'?

Thank you!


Solution

  • replace() doesn't work because there's no space character at the beginning of the filename. So there's nothing to replace.

    You also didn't add the _ character after the date.

    Just use ordinary string concatenation or formatting

    for f in os.listdir(directory):
        os.rename(os.path.join(directory, f),
                    os.path.join(directory, f"{txt_needed}_{f}"))