我正在尝试重命名Python
中的目录,这样目录将重命名为其原始名称的前8个字符。
这就是我所做的:
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)
但是我收到以下错误:
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
如何解决此错误?
感谢。
答案 0 :(得分:1)
您需要指定目录的完整路径
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)
注意:
我添加了&#34; \\&#34;对于Windows