2

I'm trying to change the name of my csv file with python. So I know that when I want a filename it gives gives a path for instance

C:/user/desktop/somefolder/[someword].csv

so what I want to do is to change this file name to something like

C:/user/desktop/somefolder/[someword] [somenumber].csv

but I don't know what that number is automatically, or the word is automatically the word was generated from another code I don't have access to, the number is generated from the python code I have. so I just want to change the file name to include the [someword] and the [somenumber] before the .csv

I have the os library for python installed incase that's a good library to use for that.

greens trial
  • 57
  • 1
  • 6

1 Answers1

2

Here is the solution (no extra libs needed):

import os

somenumber = 1  # use number generated in your code
fpath = "C:/user/desktop/somefolder"

for full_fname in os.listdir(fpath):
    # `someword` is a file name without an extension in that context
    someword, fext = os.path.splitext(full_fname)
    old_fpath = os.path.join(fpath, full_fname)
    new_fpath = os.path.join(fpath, f"{someword} {somenumber}{fext}")
    os.rename(old_fpath, new_fpath)
Lich
  • 482
  • 2
  • 10
  • 1
    upvoted - however, I suggest using `os.path.join` instead of `/` (https://stackoverflow.com/questions/13944387/why-use-os-path-join-over-string-concatenation) - also, for readability, would prefer variable names like `fname`, `fpath`, `fext`, etc... – optimus_prime Jun 29 '22 at 18:39
  • Also, I didn't know about `os.path.splitext` - pretty sweet! – optimus_prime Jun 29 '22 at 18:39