0

I think I have managed to get this resolved.Wrote a Pyhon script to rename files, but it deletes them instead of renaming them. What am I doing wrong here? I have figured out the issue with renaming. Can someone tell me why the below if statement is failing now to pull only the files that start with the word "New"?

#! /usr/bin/python

import os
import datetime
import glob

now = datetime.datetime.now()
#store date in string variable
dateStr = str(now.strftime('%Y%m%d-'))
src = r"C:\Users\username\Downloads"

for file in glob.glob(os.path.join(src, '*.txt')):
    #Grab the basename
    fileName = os.path.basename(file)
    newName =  src + "\\" + dateStr + fileName
    #THIS if statement does not work
    #if fileName.startswith("New"):
    os.rename(file, newName)
    print(newName)

Can anyone advise why the above if-statement does not work?

Ben
  • 21
  • 4
  • 3
    Doesn't `os.rename('c:/foo/bar/Newwibble.txt', '20180713-Newwibble.txt')` move the file to the current working directory, not to `c:/foo/bar/` as hoped? – Ken Y-N Jul 13 '18 at 01:05
  • Possible duplicate of [How to move a file in Python](https://stackoverflow.com/questions/8858008/how-to-move-a-file-in-python) – Ken Y-N Jul 13 '18 at 01:08
  • @KenY-N No just renaming the files then will finish the script to move them to another directory – Ben Jul 13 '18 at 01:10
  • My issue is about renaming the files NOT MOVING THEM – Ben Jul 13 '18 at 01:17
  • 1
    You are using the path in part of the command, but not in the other part of the command. I would guess all your files are at `C:\dateStr...`? Try `newName = src + r"\" + dateStr + head + tail`. And why split then just `+` back together if you aren't inserting the dateStr between...? – beroe Jul 13 '18 at 01:18
  • updated my script as above, but still having issues – Ben Jul 13 '18 at 01:41
  • Deleted this comment – Ben Jul 13 '18 at 01:42
  • 1
    Please describe how you have updated it, because as Marichyasana points out, you have introduced a new bug. Please also describe your problem in more detail than "still having issues". Finally, you should check the return value for `os.rename()` to see if any errors occur. – Ken Y-N Jul 13 '18 at 03:54
  • I have made it work now by commenting out this line if file.startswith("New"): – Ben Jul 13 '18 at 13:13

1 Answers1

0

( I ran this on my computer so the filenames don't match yours)

in the for statement the variable 'file' is a full path with filename something like

C:\Users\Philip\Downloads\PROGIDS-ON-THIS-COMPUTER.txt  

and is not changed
so when the 'if' statement checks to see if it starts with "New" it never matches

you probably want to change to use 'fileName' instead
Marichyasana
  • 2,966
  • 1
  • 19
  • 20
  • The code initially use `filename`, but it's since been edited, which is one reason it is not advised to edit code in a question too drastically, or at least without noting the change. – Ken Y-N Jul 13 '18 at 03:53