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

2024-04-29 08:02:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

所以我想把所有这些文件名改成'hardhateperson01','hardhateperson02'等等。 我尝试了下面的代码,但它一直显示错误。 你能帮我做这个吗

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

Tags: 文件代码文件夹os文件名hat错误file
2条回答

以下是解决方案:

  • 检查文件是否存在
  • 避免过度书写
  • 检查是否需要重命名
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)

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)

相关问题 更多 >