[英]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.