简体   繁体   English

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

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

I'm trying to change all the files in a folder so that they contain some unity.我正在尝试更改文件夹中的所有文件,以便它们包含一些统一性。 For example, I have 'Hard Hat Person01', 'Hard Hat Person02' and so on but I also have 'hard_hat_person01' and 'hardhatperson01' in the same folder.例如,我有“Hard Hat Person01”、“Hard Hat Person02”等等,但我在同一个文件夹中还有“hard_hat_person01”和“hardhatperson01”。

So I want to change all those file names into 'hardhatperson01', 'hardhatperson02' and so on.所以我想将所有这些文件名更改为“hardhatperson01”、“hardhatperson02”等。 I tried the codes as below but it keeps showing errors.我尝试了以下代码,但它一直显示错误。 Can you please help me with this?你能帮我解决这个问题吗?

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

listdir only returns the filename, not its directory. listdir只返回文件名,而不是它的目录。 And you can't rename the file more than once.并且您不能多次重命名文件。 In fact, you should make sure that you don't accidentally overwrite an existing file or directory.事实上,您应该确保不会意外覆盖现有文件或目录。 A more robust solution is一个更强大的解决方案是

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)

Here is the solution:这是解决方案:

  • To check if file is present检查文件是否存在
  • Avoid over writing避免过度书写
  • Checking if rename is required or not检查是否需要重命名
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