0

I am new to Python coding so here a question. I want to find files that are called "untitled" with any kind of extension, e.g. jpg, indd, psd. Then rename them to the date of the current day.

I have tried the following:

import os

for file in os.listdir("/Users/shirin/Desktop/Artez"):
    if file.endswith("untitled.*"):
        print(file)

When I run the script, nothing happens.

1
  • Don't you mean if file.startswith("untitled")? Commented Mar 2, 2016 at 17:34

4 Answers 4

1

You might find the glob function more useful in this situation:

import glob

for file in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"):
    print(file)

Your function does not print anything as there are probably no files ending with .* in the name. The glob.glob() function will carry out the file expansion for you.

You can then use this to do your file renaming as follows:

import glob
import os
from datetime import datetime

current_day = datetime.now().strftime("%Y-%m-%d")

for source_name in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"):
    path, fullname = os.path.split(source_name)
    basename, ext = os.path.splitext(fullname)
    target_name = os.path.join(path, '{}{}'.format(current_day, ext))
    os.rename(source_name, target_name)

A Python datetime object can be used to get you a suitable timestamp.

Sign up to request clarification or add additional context in comments.

Comments

0

Python string comparator does not support wildcards. You can search for "untitled." anywhere in the text:

import os
    for file in os.listdir("/Users/shirin/Desktop/Artez"):
        if "untitled." in file:
            print(file)

keep in mind that this will include any file that has "untitled." at any location of the file.

Comments

0

try with this approach

import os
directoryPath = '/Users/shirin/Desktop/Artez'
lstDir = os.walk(directoryPath) 
for root, dirs, files in lstDir:
  for fichero in files:        
    (filename, extension) = os.path.splitext(fichero)
    if filename.find('untitle') != -1: # == 0 if starting with untitle
         os.system('mv '+directoryPath+filename+extension+' '+directoryPath+'$(date +"%Y_%m_%d")'+filename+extension)

Comments

0
import os

for file in os.listdir("/Users/shirin/Desktop/Artez"):
   if(file.startswith("untitled")):
      os.rename(file, datetime.date.today().strftime("%B %d, %Y") + "." +  file.split(".")[-1])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.