【问题标题】:Python - how to change all file names into lowercases and without blanksPython - 如何将所有文件名更改为小写且不带空格
【发布时间】:2020-05-25 09:44:18
【问题描述】:

我正在尝试更改文件夹中的所有文件,以便它们包含一些统一性。 例如,我有“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())

【问题讨论】:

    标签: python rename file-rename


    【解决方案1】:

    解决办法如下:

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

    【讨论】:

      【解决方案2】:

      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)
      

      【讨论】:

        猜你喜欢
        • 2020-07-10
        • 2011-04-07
        • 2021-07-17
        • 1970-01-01
        • 2021-10-08
        • 2014-02-02
        • 2014-12-04
        • 2011-12-08
        • 2017-11-08
        相关资源
        最近更新 更多