Reputation: 21
I'm trying to a script to rename to the date that it was sent as an email(which is the first part of the script but doesn't matter for this part) then to rename, and sort it into a 'Complete' folder. This is what my code looks like
Edit - I have all the imported stuff way up at the top and i didnt show it, but i assume i have the right stuff imported if you would like to see just ask
dir5 = "C:\\Users\\Michael D\\Documents\\Test\\AmLit"
dir6 = "C:\\Users\\Michael D\\Documents\\Test\\History"
dir7 = "C:\\Users\\Michael D\\Documents\\Test\\MultiLit"
dir8 = "C:\\Users\\Michael D\\Documents\\Test\\Physics"
dir5_final = "C:\\Users\\Michael D\\Documents\\TestMove\\AmLit"
dir6_final = "C:\\Users\\Michael D\\Documents\\TestMove\\History"
dir7_final = "C:\\Users\\Michael D\\Documents\\TestMove\\MultiLit"
dir8_final = "C:\\Users\\Michael D\\Documents\\TestMove\\Physics"
now = datetime.datetime.now()
now1 = (str(now.day) + '/' + str(now.month) + '/' + str(now.year))
dir5_files = os.listdir(dir5)
dir6_files = os.listdir(dir6)
dir7_files = os.listdir(dir7)
dir8_files = os.listdir(dir8)
for f in dir5_files:
if (f.startswith("A") or f.startswith("a")):
os.rename(f, now1 + " " + f)
but i keep getting this error
RESTART: C:/Users/Michael D/Documents/Coding/Schoolwork Email/Email Sender Beta 1.7.21.9.16.py
Traceback (most recent call last):
File "C:/Users/Michael D/Documents/Coding/Schoolwork Email/Email Sender Beta 1.7.21.9.16.py", line 148, in <module>
os.rename(f, now1 + " " + f)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'A Test.txt' -> '21/9/2016 A Test.txt'
any thoughts as to what I'm doing wrong?
Upvotes: 2
Views: 6034
Reputation: 140276
2 errors:
You are not in the current directory
You just cannot have slashes in the names. The filesystem won't allow it as it is (alternately) used to separate path parts.
First, generate the date directly with underscores:
now1 = (str(now.day) + '_' + str(now.month) + '_' + str(now.year))
Then replace
os.rename(f, now1 + " " + f)
by
os.rename(os.path.join(dir5,f), os.path.join(dir5,now1.replace("/","_") + " " + f))
and A Test.txt
would be renamed to 21_9_2016 A Test.txt
in the directory you specified.
Upvotes: 5