在Python中重命名目录 [英] Renaming a directory in Python
本文介绍了在Python中重命名目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 Python
中重命名目录,这样的目录将被重命名为其原始名称的前8个字符.
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.
这就是我所做的:
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
如何解决此错误?
谢谢.
推荐答案
您需要指定目录的完整路径
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)
注意:
我为Windows添加了"\\"
I have added "\\" for windows
这篇关于在Python中重命名目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文