I want to change files with extension ".py" to ".txt" for all files within folders and subfolders. What I did with my code is :
def py_to_txt(directory):
for foldername, subfolders, filenames in os.walk(dire):
print(filenames)
for f in filenames :
if f.endswith('.py'):
base = os.path.splitext(f)[0]
os.rename(f, base + '.txt')
and this code only changes the first file extension in the parent directory and then throws the following error :
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-69-ed0d85ebad81> in <module>
----> 1 py_to_txt(dire)
<ipython-input-68-1efd842876ed> in py_to_txt(directory)
5 if f.endswith('.py'):
6 base = os.path.splitext(f)[0]
----> 7 os.rename(f, base + '.txt')
8
FileNotFoundError: [Errno 2] No such file or directory: 'file2.py' -> 'file2.txt'
What is the right way of doing it ?