Home > OS >  Edit CSV filename in Python to append to the current filename
Edit CSV filename in Python to append to the current filename

Time:06-30

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.

CodePudding user response:

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)
  • Related