重命名Windows目录中的文件

时间:2016-01-13 20:25:58

标签: python python-2.7 file-rename listdir

我目前正在尝试通过编写一个脚本来学习python,该脚本将通过保留对象的名称来清理我的下载文件夹,同时从文件夹/文件名中删除特殊字符和额外数据。

即:

../Completed Downloads/random.download.here.x264.team
../Completed Download/random download here

以及

file.name.randomstring_randomstring.mkv
file name randomstring randomstring (date).mkv

我现在已经搜索了一段时间,但是虽然我可以创建一个可以看到这些文件的脚本 - 但我似乎无法将其添加到每个特殊字符并重命名。当我这样做时,我得到:

Traceback (most recent call last):
  File "C:\Python27\Scripts\plexprep.py", line 7, in <module>
    os.rename(dir, dir.replace(".", "").lower())
WindowsError: [Error 2] The system cannot find the file specified

这是我的剧本的开头:

import fnmatch
import os

#Matches directories for Plex and renames directories to help Plex crawl.
for dir in os.listdir('F:\Downloads\Completed Downloads'):
    if fnmatch.fnmatch(dir, '*'):
        os.rename(dir, dir.replace(".", "").lower())

#Matches filenames for Plex and renames files/subdirectories to help Plex crawl.

1 个答案:

答案 0 :(得分:0)

正如@ cricket_007在评论中所说,你应该通过在路径前添加r来逃避反斜杠:

for dir in os.listdir(r'F:\Downloads\Completed Downloads'):

然而,WindowsError是由其他内容引起的:在您的循环中,dir只会是子文件夹的名称,而不是它的完整路径。可能的解决方案是:

base = r'F:\Downloads\Completed Downloads'
for dir in os.listdir(base):
    path = os.path.join(base, dir)
    # Now use your os.rename() logic