this code is meant to ask for a directory, then list al files in that directory, then rename then to their position in that list, problem is I always get error 2, file not found, while if i print the list it apperently does find the files because the list is not blank.
import os, sys
path = input("input path: ")
dirs = os.listdir(path)
for i in range(0,len(dirs)):
os.rename(dirs[i], str(i))
Given input files, I want to rename the base file name with a number, but preserving the file extension. Thus
Input
‘a.txt’, ‘test.txt’, ‘test1.txt’
Output
‘0.txt’, ‘1.txt’, ‘2.txt’
Yup, so you do need to add the code from my comment. The problem is os.listdir is only returning base file names so when the rename is called, it expects to find those files in whatever directory Python thinks it should be in. By adding the os.path.join, it will build out the fully qualified path to the file so the rename will work correctly.
In the comments, OP stated the files got moved up a folder which lead me to believe the rename needed a fully qualified path on second argument. Also, we learned the files should not be renamed from foo.txt to 0 but instead should become 0.txt etc (preserving file extension) This code now
Verified with Python 2.6.1
Showing the relevant bits from the command line. You can see the empty files bar.txt and foo.txt are renamed to 0 and 1