擅长:python、mysql、java
<p><code>listdir</code>只返回文件名,不返回其目录。并且不能多次重命名该文件。事实上,您应该确保不会意外地覆盖现有文件或目录。更稳健的解决方案是</p>
<pre><code>import os
basedir = r'C:\Document'
for name in oslistdir(basedir):
fullname = os.path.join(basedir, name)
if os.path.isfile(fullname):
newname = name.replace(' ', '').lower()
if newname != name:
newfullname = os.path.join(basedir, newname)
if os.path.exists(newfullname):
print("Cannot rename " + fullname)
else:
os.rename(fullname, newfullname)
</code></pre>