0

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 for the first two words, and I do not want those words in my finale file name. These words are variables. Any assistance would be appreciated. Thanks!

Calvin Cheng
  • 35,640
  • 39
  • 116
  • 167
  • I am fairly new to python so am trying to learn regular expression, split/joint for extracting. I can do a rename of a straight file name, but am trying to extract the file name based on the words consistent pattern/character to extract what I need. – user1801715 Nov 06 '12 at 01:34
  • I've done glob in conjunction with .rename, but that doesn't account for the wildcards. – user1801715 Nov 06 '12 at 01:36
  • 1
    It is usually helpful to include that information on the question it self, usually with the exact code you've tried. It shows people that you have spent time trying on your own before posting the question and also gives them a starting point on where to look for problems or sources of confusion for you. Just a friendly tip. – yarian Nov 06 '12 at 01:38
  • 2
    I do apologize. I am learning python, and this is my first time using the site. I will read on the etiquette and improve my efforts. Thank you! – user1801715 Nov 06 '12 at 01:48
  • 2
    If everyone had that attitude :) – yarian Nov 06 '12 at 01:49

2 Answers2

2

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
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
1
import os

myfilename = "~test1~test2~filename.csv"

for filename in os.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!

Calvin Cheng
  • 35,640
  • 39
  • 116
  • 167