Reputation: 3
I want to rename all the files in test folder as 1, 2, 3 and so on
import os, sys, path
path = r"F:\test"
dirs = os.listdir(path)
print(dirs)
count = 1
for files in dirs:
str1 = str(count)
os.rename(files, str1)
count += 1
but my code giving me this error: WindowsError: [Error 2] The system cannot find the file specified
Upvotes: 0
Views: 1066
Reputation: 9275
Just add one line to change bthe current working directory.
import os, sys, path
path = r"F:\test"
dirs = os.listdir(path)
os.chdir(path) # Change the current working directory
print(dirs)
count = 1
for files in dirs:
str1 = str(count)
os.rename(files, str1)
count += 1
Upvotes: 0
Reputation: 323
dirs
is a list of paths, and iterating through it won't give you the contents of the directories. You would need another os.listdir
for that.
Also, to rename the files, you have to go through each of them.
A better solution would've been:
import os
count = 1
path = r"F:\test"
for root, dirs, files in os.walk(path):
for filename in files:
os.rename(os.path.join(root, filename), os.path.join(root, str(count)))
count += 1
Upvotes: 1