我试着用波纹管提到的代码来重命名一些文件。但是这个相同的代码在Linux中运行良好但在Windows中运行不正常。 CODE
#!/usr/bin/env python
from os import listdir
import os
from os.path import isfile, join
mypath = 'D:\\Hadoo'
path = 'D:\\Hadoo'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
Existing = []
repeated = []
for a in onlyfiles:
f = a.index('}')
b = a[f + 1:]
Existing.append(b)
os.rename(os.path.join(mypath, a), os.path.join(path, b))
InLinux输入:
file{}a1.txt , file{}a2.txt
InLinux输出:
a1.txt , a2.txt
但Windows中没有发生同样的情况。它通过以下错误:
>python filer.py
Traceback (most recent call last):
File "filer.py", line 16, in <module>
os.rename(os.path.join(mypath, a), os.path.join(path, b))
WindowsError: [Error 183] Cannot create a file when that file already exists