1

I'm trying to rename a directory in Python, such hat the directory will be renamed to its first 8 characters of its original name.

This is what I did:

import os

path = '/home/directories'

for root, dirs, files in os.walk(path):
    for directory in dirs:
        new_name = directory[0:8]
        os.rename(directory, new_name)

I however get the following error:

Traceback (most recent call last):   
File "xyz.py", line 8, in <module>
    os.rename(directory, new_name) 
OSError: [Errno 2] No such file or directory

How can I solve this error?

Thanks.

Sraw
  • 18,892
  • 11
  • 54
  • 87
Simplicity
  • 47,404
  • 98
  • 256
  • 385

1 Answers1

1

You need to specify full path of directory

import os

path = 'C:\\Users\\demo_test_eg'

for root, dirs, files in os.walk(path):
    for directory in dirs:
       new_name = directory[0:8]
       path1 = path + "\\"+ directory#Full path of directory
       new_path = path + "\\"+new_name#Full path of file whose name is changed
       os.rename(path1, new_path)

Note :

I have added "\\" for windows

sachin dubey
  • 755
  • 9
  • 28