使用Python对文件进行批量改名
Python在Windows系统下的路径表示回顾:反斜杠“\”是转义符,如果继续用windows习惯使用“\”表示文件路径,就会产生歧义。
Windows下的原始路径:C:\Users\LUO\Documents\GitHub\CalculatorT3000\introduction
所以在Python中有三种方法表示:
path="C:\\Users\\LUO\\Documents\\GitHub\\CalculatorT3000\\introduction\\"
path=r'C:\Users\LUO\Documents\GitHub\CalculatorT3000\introduction\'
path='C:/Users/LUO/Documents/GitHub/CalculatorT3000/introduction/'
使用斜杠“/”: 'C:/Users/LUO/Documents/GitHub/CalculatorT3000/introduction/'
将反斜杠符号转义: "C:\\Users\\LUO\\Documents\\GitHub\\CalculatorT3000\\introduction\\" 因为反斜杠是转义符,所以两个"\\"就表示一个反斜杠符号
使用Python的raw string:r'C:\Users\LUO\Documents\GitHub\CalculatorT3000\introduction\' python下在字符串前面加上字母r,表示后面是一个原始字符串raw string,不过raw string主要是为正则表达式而不是windows路径设计的,所以这种做法尽量少用,可能会出问题
使用os 模块来处理文件和目录
python 对文件进行批量改名用到的是 os 模块中的 listdir 方法和 rename 方法。
os.listdir(dir) : 获取指定目录下的所有子目录和文件名
os.rename(原文件名,新文件名) :os.rename(src, dst) 方法用于命名文件或目录,从 src 到 dst,如果dst是一个存在的目录, 将抛出OSError
os.renames() 方法用于递归重命名目录或文件。类似rename()
os.renames(old, new)
old -- 要重命名的目录
new --文件或目录的新名字。甚至可以是包含在目录中的文件,或者完整的目录树
os.getcwd() 返回当前工作目录
os.path 模块主要用于获取文件的属性
os.path.basename(path) | 返回文件名 |
os.path.dirname(path) | 返回文件路径 |
os.path.exists(path) | 如果路径 path 存在,返回 True;如果路径 path 不存在,返回 False。 |
os.path.getmtime(path) | 返回最近文件修改时间 |
os.path.getctime(path) | 返回文件 path 创建时间 |
os.path.getsize(path) | 返回文件大小,如果文件不存在就返回错误 |
os.path.isfile(path) | 判断路径是否为文件 |
os.path.isdir(path) | 判断路径是否为目录 |
os.path.samefile(path2, path3) | 判断目录或文件是否相同 |
os.path.sameopenfile(fp1, fp2) | 判断fp1和fp2是否指向同一文件 |
import os #三种路径表示方法 #path="C:\\Users\\LUO\\Documents\\GitHub\\CalculatorT3000\\introduction\\" #转义符的方式不能在此使用 #path=r'C:\Users\LUO\Documents\GitHub\CalculatorT3000\introduction\' #path='C:/Users/LUO/Documents/GitHub/CalculatorT3000/introduction/' #从控制台输入 path=input("请输入需要改名的路径:") #判断路径是否存在 if os.path.exists(path): #获取该目录下所有文件,存入列表中 fileList=os.listdir(path) n=0 for i in fileList: #设置旧文件名(就是路径+文件名) oldname=path+ os.sep + fileList[n] # os.sep添加系统分隔符 #判断当前是否是文件 if os.path.isfile(oldname): #设置新文件名 newname=path + os.sep +'calc_'+str(n+1)+'.jpg' os.rename(oldname,newname) #用os模块中的rename方法对文件改名 print(oldname,'======>',newname) n+=1 else: print('路径不存在')
补充:使用python批量修改文件名
使用python对文件名进行批量修改
使用split方法对原文件名进行切分,选择需要的部分进行保留做为新的文件名,也可添加字段。
函数说明
split()函数
语法:str.split(str="",num=string.count(str))[n]
参数说明:
str: 表示为分隔符,默认为空格,但是不能为空(’’)。若字符串中没有分隔符,则把整个字符串作为列表的一个元素
num:表示分割次数。如果存在参数num,则仅分隔成 num+1 个子字符串,并且每一个子字符串可以赋给新的变量
[n]: 表示选取第n个分片
注意:当使用空格作为分隔符时,对于中间为空的项会自动忽略
import os import re def changename(orignname): picture=os.listdir(orignname) for filename in picture: # filename1 = filename.split(".")[0] # filename2=re.findall(r"\d+\.?\d*", filename1)[0]+".png" # srcpath = os.path.join(orignname,filename) # allpath = os.path.join(orignname,filename2) # os.rename(srcpath,allpath) #split("_",2)[1] “_”表示分隔符 ; 2表示分割次数 ; [1]表示选取第 i 个片段 filename1=filename.split("_")[3] #设置旧文件名(就是路径+文件名) srcpath=os.path.join(orignname,filename) #设置新文件名 allpath= os.path.join(orignname,filename1) os.rename(srcpath, allpath) if __name__ == '__main__': orignname=r"D:\AK\GJ\dataset_2\val\labels" changename(orignname)
注意:该方法是直接覆盖原图的文件名,不另存,如果想要保留原文件名,请提前复制
The above is the detailed content of How to batch rename files using Python. For more information, please follow other related articles on the PHP Chinese website!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.