Skip to content Skip to sidebar Skip to footer

Extract Values/renaming Filename In Python

I am trying to use python to rename a filename which contains values such as: ~test1~test2~filename.csv I want to rename the file to filename.csv. The tildes being my separator f

Solution 1:

Since the words change for each file name its best to search a directory for files that match a pattern. glob does that for you.

If you have a directory like this:

.
├── ~a~b~c.csv
├── file.csv
├── ~foo~bar~f1.csv
└── hello.txt

Then running this:

import os, glob
for f in glob.glob('~*~*~*.csv'):
    os.rename(f,f.split('~')[-1])

Will give you:

.
├── c.csv
├── f1.csv
├── file.csv
└── hello.txt

Solution 2:

import os

myfilename = "~test1~test2~filename.csv"for filename inos.listdir("."):
   if filename == myfilename:
       myfilename_new = myfilename.split("~")[-1]
       os.rename(filename, myfilename_new)

Assuming of course that your original file ~test1~test2~filename.csv exists in the "current/same directory" that this python script runs.

Hope this helps you in your learning journey!

Welcome to Python!

Post a Comment for "Extract Values/renaming Filename In Python"