python/powershell_识别英文字母(a-zA-Z)/重命名文件/为文件批量添加前缀序号以便于用终端打开文件(补全长文件名)/指定/操作文件中文文件_提取并重命名win10/11的锁屏图

note1

以下程序尚未考虑健壮性
只是以添加后缀为主要目的,按照自然数序来作为新名称

关于以下使用的路径,根据自身情况替换

note2

  • 不可以在新文件名中包含非法字符
  • 基于python的重命名实现:描述文件时,要么使用绝对路径,要么使用os.chdir()切换路径后直接使用名字,否则无法重命名
  • 基于powershell的重命名实现:代码可以更加简介,这是系统shell的优势,但是该语言没有像python那样普及

基于python实现:

以<时间+n>为文件名

提取并重命名win10/11的锁屏图

import os
import os.path as op
import time
dirName="C:/Users/cxxu_11/AppData/Local/Packages/Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy/LocalState/Assets"
def renameFiles(dirName='.'):
items=os.listdir(dirName)
index=0
# there use os.chdir() to reset the current working directory;of course,you can use absolute path rather than fileName
os.chdir(dirName)
print(os.getcwd())
for item in items:
index+=1
# newName=str(index)+".jpg"
time_string = time.strftime(
'%Y-%m-%d %H-%M-%S', time.localtime(time.time()))
time_string=time_string+" "+str(index)
newName= time_string+'.jpg'
if not op.exists(newName):
os.rename(item,newName)
print(item)
if __name__=="__main__":
print("test")
renameFiles(dirName)

以00,01,02,03为文件名

import os
import os.path as op
dirName="C:/Users/cxxu/AppData/Local/Packages/Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy/LocalState/Assets"
def renameFiles(dirName='.'):
items=os.listdir(dirName)
index=1
# there use os.chdir() to reset the current working directory;of course,you can use absolute path rather than fileName
os.chdir(dirName)
for item in items:
index+=1
newName=str(index)+".jpg"
if not op.exists(newName):
os.rename(item,newName)
print(item)
if __name__=="__main__":
renameFiles(dirName)

以00_,01_,02_,…为前缀开头的防止重名的版本

import os
import os.path as op
from sys import argv, setprofile
import time
""" 使用说明,重命名文件是高危操作,为了安全起见,您可以将要被处理的文件做一个备份
其次,您可以复制文件中的一部分来测试您的代码的可行性
最后,如果代码中通过保守的预览代码代替实际的重命名操作也是不错的选择(待预览效果符合预期后执行实际的重命名操作是推荐的做法)
本程序只对文件执行重命名(纳入排序计算),文件夹被可以排除,当然,也可以认为修改使得文件夹也一并纳入计算
"""
testDir = "d:/repos/learnDatabase_sql/materials"
testDir = "D:\\org\\Ecloud\\myMusic\\hitomiShimatani"
# testDir = argv[1]
""" 设计为递归函数,不同深度的递归调用之间只有index会有所不同 """
def noRepeate(item, index, separator, itemList):
new_prefix = str(index+1).zfill(2)+separator
new_name = new_prefix+item
# 制作初步的new_name
if new_name in itemList:
# 重新制作new_name(因为发生重名),以覆盖初步的new_name
new_prefix = str(index+1).zfill(2)+separator
new_name = new_prefix+item
return noRepeate(item,index+1,separator,itemList)
# 没后重名,直接返回本次调用的初步制作的new_name
return new_name
def rename_prefix(testDir="."):
# 测试目录填入一下括号中(字符串)
os.chdir(testDir)
itemList = os.listdir(".")
currentDirItems=itemList[:]
# print(currentDirItems)
is_beginAscii = False
# 推荐的分割符,如果不喜欢,可以替换(取消的换就将其置为空字符串"")
separator = "_"
cleanList = []
# 给部分去除源文件名的前缀中的ascii码部分(可以改为数字isdigital(这在排错序号重新排序前的清洗操作是横有用的))
for item in itemList:
is_continue = item[0].isdigit() or item[0] == separator
if is_continue:
new_name = ""
# 文件名预处理与清理
for index, chr in enumerate(item):
if chr.isdigit() or chr == separator:
continue
else:
new_name = item[index:]
# print(new_name)
break
# 文件判断与重命名
if op.isfile(item):
# print(new_name)
# 由于这里还是字符串处理阶段,可以只是预览,不必执行重命名操作
# os.rename(item, new_name)
cleanList.append(new_name)
else:
...
# 得到中文名开头的文件名
needNumberList = []
for item in itemList:
isNeedNumber = not item[0].isascii()
if isNeedNumber:
needNumberList.append(item)
else:
...
itemList = needNumberList
# sort with the same format 01~99
for index, item in enumerate(itemList):
# 这里使用了字符串的.zfill来前置补零格式化字符串(对数字格式化的话可以用str()将其转为字符类型,然后执行该函数)
# 通过序数前置补0对其的处理,可以是的排序的时候不会出现错乱,当然,这需要对您的文件数(或者说数量级)做一个估计(如果文件在100个以内,哪个zfill()参数取2较为合适.一次类推)
# 我还建议在插入序号前缀中的最后一个字符以"_"结尾或者其他合法的字符来分隔
new_prefix = str(index).zfill(2)+separator
new_name = new_prefix+item
# for index, chr in enumerate(item):
# if op.isfile(item):
# 在执行重命名操作前但应出来预览一下,符合预期后在编写重命名语句
originName = item
previewString = f'😎newName:{new_name}<-😁originName:{originName}'
# debug
# print(itemList)
while( (new_name in currentDirItems)):
print(f'already exist the new_name:{new_name}🤣')
new_prefix = str(index+1).zfill(2)+separator
new_name = new_prefix+item
# if new_name in itemList:
# print(originName, new_name)
print(previewString)
os.rename(originName, new_name)
if __name__ == "__main__":
rename_prefix()

基于powershell实现

预览效果

执行之前:


执行代码以及之后的结果:

$i=1
Get-ChildItem * | ForEach-Object {
rename $_.Name ($i.toString() + $_.Name);
$i += 1 ;
}

执行之前把rename改为write查看预览效果

$i=1
Get-ChildItem * | ForEach-Object {
write ($i.toString() + $_.Name);
$i += 1 ;
}

为文件批量添加前缀序号以便于用终端指定/操作文件中文文件

import os
import os.path as op
import time
""" 使用说明,重命名文件是高危操作,为了安全起见,您可以将要被处理的文件做一个备份
其次,您可以复制文件中的一部分来测试您的代码的可行性
最后,如果代码中通过保守的预览代码代替实际的重命名操作也是不错的选择(待预览效果符合预期后执行实际的重命名操作是推荐的做法)
本程序只对文件执行重命名(纳入排序计算),文件夹被可以排除,当然,也可以认为修改使得文件夹也一并纳入计算;当然,您可以将os.isfile()改为os.isdir()来对文件夹进行重命名而干扰文件
"""
if __name__ == "__main__":
# 测试目录填入一下括号中(字符串)
os.chdir("D:\\org\\Ecloud\\myMusic\\hitomiShimatani")
itemList = os.listdir(".")
is_beginAscii = False
# 推荐的分割符,如果不喜欢,可以替换(取消的换就将其置为空字符串"")
separator = "_"
cleanList = []
# 给部分去除源文件名的前缀中的ascii码部分(可以改为数字isdigital(这在排错序号重新排序前的清洗操作是横有用的))
for item in itemList:
is_continue = item[0].isdigit() or item[0] == separator
if is_continue:
new_name = ""
# 文件名预处理与清理
for index, chr in enumerate(item):
if chr.isdigit() or chr == separator:
continue
else:
new_name = item[index:]
# print(new_name)
break
# 文件判断与重命名
if op.isfile(item):
print(new_name)
# 由于这里还是字符串处理阶段,可以只是预览,不必执行重命名操作
# os.rename(item, new_name)
cleanList.append(new_name)
else:
...
# itemList = cleanList
# sort with the same format 01~99
for index, item in enumerate(itemList):
# 这里使用了字符串的.zfill来前置补零格式化字符串(对数字格式化的话可以用str()将其转为字符类型,然后执行该函数)
# 通过序数前置补0对其的处理,可以是的排序的时候不会出现错乱,当然,这需要对您的文件数(或者说数量级)做一个估计(如果文件在100个以内,哪个zfill()参数取2较为合适.一次类推)
# 我还建议在插入序号前缀中的最后一个字符以"_"结尾或者其他合法的字符来分隔
new_prefix = str(index).zfill(2)
new_prefix = new_prefix+separator
new_name = new_prefix+item
# for index, chr in enumerate(item):
if op.isfile(item):
# 在执行重命名操作前但应出来预览一下,符合预期后在编写重命名语句
print(new_name)
os.rename(item, new_name)

终端操作效果

终端点歌:

带分析版本

  • 将指定目录(当前目录)下的文件修改为便于终端补全的格式:
  • 可以借助powershell/bash调用此脚本
import os
import os.path as op
from sys import argv, setprofile
import time
from venv import create
""" 使用说明,重命名文件是高危操作,为了安全起见,您可以将要被处理的文件做一个备份
其次,您可以复制文件中的一部分来测试您的代码的可行性
或者,编写一个专门的测试(TDD)
最后,如果代码中通过保守的预览代码代替实际的重命名操作也是不错的选择
(待预览效果符合预期后执行实际的重命名操作是推荐的做法)
本程序只对文件执行重命名(纳入排序计算),文件夹不处理
使用python脚本,跨平台
-----
需求分析
- 首先,能够将非字母&数字开头的文件重命名为以指定格式命名的文件:例如,"00_"+文件名
换句话说,经过函数处理,原先不满足字母|数字开头的文件名改为形如"00_"+文件名的格式
算法:
- 将目录下文件名读入到一个列表保存备用
- 识别并提取出需要做重命名的文件(但是先仅仅做文件名上的变更预览(old->new的格式预览),如果符合预期,则编写相应的IO操作代码)
"""
# testDir = argv[1]
""" 设计为递归函数,不同深度的递归调用之间只有index会有所不同 """
def drop_duplicated(item, index, separator, itemList):
"""用于去重,一般情况下不调用它!"""
new_prefix = str(index+1).zfill(2)+separator
new_name = new_prefix+item
# 制作初步的new_name
if new_name in itemList:
# 重新制作new_name(因为发生重名),以覆盖初步的new_name
new_prefix = str(index+1).zfill(2)+separator
new_name = new_prefix+item
return drop_duplicated(item,index+1,separator,itemList)
# 没后重名,直接返回本次调用的初步制作的new_name
return new_name
def rename_prefix(testDir="."):
# 测试目录填入
os.chdir(testDir)
itemList = os.listdir(".")
# clone 当前目录下的文件名列表备用
currentDirItems=itemList[:]
print(currentDirItems)
# 推荐的分割符,如果不喜欢,可以替换(取消的换就将其置为空字符串"")
separator = "_"
not_meet = []
for item in itemList:
# isalnum无法排除中文
# is_need_rename = not item[0].isalnum()
first_char=item[0]
is_english_alpha =first_char.islower() or first_char.isupper()
is_valid=is_english_alpha or first_char.isdigit()
# is_need_rename = not is_english_alpha and first_char.isdigit()
# if not valid ,then do some handling!
if not is_valid:
not_meet.append(item)
else:
...
itemList = not_meet
print("@itemList",itemList)
# sort with the same format 01~99
for index, item in enumerate(itemList):
# 这里使用了字符串的.zfill来前置补零格式化字符串(对数字格式化的话可以用str()将其转为字符类型,然后执行该函数)
# 通过序数前置补0对其的处理,可以是的排序的时候不会出现错乱,当然,这需要对您的文件数(或者说数量级)做一个估计(如果文件在100个以内,哪个zfill()参数取2较为合适.一次类推)
# 我还建议在插入序号前缀中的最后一个字符以"_"结尾或者其他合法的字符来分隔
new_prefix = str(index).zfill(2)+separator
new_name = new_prefix+item
# for index, chr in enumerate(item):
# if op.isfile(item):
# 在执行重命名操作前但应出来预览一下,符合预期后在编写重命名语句
originName = item
preview_variations = f'😎newName:{new_name}<-😁originName:{originName}'
# debug
# print(itemList)
while( (new_name in currentDirItems)):
print(f'already exist the new_name:{new_name}🤣')
new_prefix = str(index+1).zfill(2)+separator
new_name = new_prefix+item
# if new_name in itemList:
# print(originName, new_name)
print(preview_variations)
os.rename(originName, new_name)
def create_files(n:int=2,path:str="."):
""" 这是一个创建测试文件的函数,用以检测脚本的主要逻辑是否可以大致的正确工作 """
path="test_rename_dir"
if(not os.path.exists(path)):
os.mkdir(path)
os.chdir("test_rename_dir")
# os.chdir(path)
mode="w+"
for i in range(n):
with open(f"{i}.txt", mode) as f:
f.write("hello world")
with open("中文开头文件",mode) as f:
f.write("中文开头文件")
with open("(_ascii文件", mode) as f:
f.write("(_ascii文件")
if __name__ == "__main__":
# print(f'please close any files and directories you want to rename,if they are used by other program.😁')
print('😎------------------------------')
#create_files()
rename_prefix()

python 识别英文字母(a-z,A-Z)

eng_alpha="a"
chinese_alpha="中"
## 方案0:isalpha(),无法区分中文字母(汉字)和英文字母A-Za-z
## 方案1:
def is_eng_alpha(char):
return char.islower() or char.isupper()
## 方案2:(判断所给字符是否为英文字母)
def is_eng_alpha2(char):
if char>="a" and char<='z' or char>="A" and char<='Z':
print("char is english alpha")
return True
else:
print("char is not english alpha")
return False
if __name__=="__main__":
is_eng_alpha2(eng_alpha)
is_eng_alpha2(chinese_alpha)
posted @   xuchaoxin1375  阅读(8)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示