繁体   English   中英

Python - 如何将所有文件名更改为小写且不带空格

[英]Python - how to change all file names into lowercases and without blanks

我正在尝试更改文件夹中的所有文件,以便它们包含一些统一性。 例如,我有“Hard Hat Person01”、“Hard Hat Person02”等等,但我在同一个文件夹中还有“hard_hat_person01”和“hardhatperson01”。

所以我想将所有这些文件名更改为“hardhatperson01”、“hardhatperson02”等。 我尝试了以下代码,但它一直显示错误。 你能帮我解决这个问题吗?

for file in os.listdir(r'C:\Document'):
    if(file.endswith('png')):
        os.rename(file, file.lowercase())
        os.rename(file, file.strip())

listdir只返回文件名,而不是它的目录。 并且您不能多次重命名文件。 事实上,您应该确保不会意外覆盖现有文件或目录。 一个更强大的解决方案是

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)

这是解决方案:

  • 检查文件是否存在
  • 避免过度书写
  • 检查是否需要重命名
import os
os.chdir(r"C:\Users\xyz\Desktop\tESING")
for i in os.listdir(os.getcwd()):
    if(i.endswith('png')) and " " in i and any(j.isupper() for j in i):
        newName = i.lower().replace(" ","")
        if newName not in os.listdir(os.getcwd()):
            os.rename(i,newName)
        else:
            print("Already Exists: ",newName)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM