How to batch rename files using Python
使用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!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

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.

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

Developing a GitLab plugin on Debian requires some specific steps and knowledge. Here is a basic guide to help you get started with this process. Installing GitLab First, you need to install GitLab on your Debian system. You can refer to the official installation manual of GitLab. Get API access token Before performing API integration, you need to get GitLab's API access token first. Open the GitLab dashboard, find the "AccessTokens" option in the user settings, and generate a new access token. Will be generated

Configuring an HTTPS server on a Debian system involves several steps, including installing the necessary software, generating an SSL certificate, and configuring a web server (such as Apache or Nginx) to use an SSL certificate. Here is a basic guide, assuming you are using an ApacheWeb server. 1. Install the necessary software First, make sure your system is up to date and install Apache and OpenSSL: sudoaptupdatesudoaptupgradesudoaptinsta

Apache is the hero behind the Internet. It is not only a web server, but also a powerful platform that supports huge traffic and provides dynamic content. It provides extremely high flexibility through a modular design, allowing for the expansion of various functions as needed. However, modularity also presents configuration and performance challenges that require careful management. Apache is suitable for server scenarios that require highly customizable and meet complex needs.
