用python批量修改文件名,python批量修改文件格式

  用python批量修改文件名,python批量修改文件格式

  使用python批量修改文件名时,有时会遇到几个格式不正确的文件名,需要逐个修改。比如从test1.py,test_2.py,…,testn.py换成test_1.py,…,test_n.py时,如果文件数量少,可以手动更改,但是如果文件多,就不要手动更改了。

  要批量修改文件名,必须先获取所有文件名,批量替换几个文件名。你需要提取想要的部分,然后拼接成一个新的文件名,实现文件名替换。按照这三个步骤,首先要获取所有文件名,使用os.listdir()方法,无传递参数是获取当前文件路径下所有文件和文件夹的列表。

  导入osprint(os.listdir())输出结果:

  d:\ GitHub \自动重复\。venv \ Scripts \ python . exe D:/GitHub/auto-repeat/replace _ filename/main . py[ main . py , test1.py , test2.py , test3.py ,__init__。py]最初,我想通过for循环提出带有test的文件,然后用“.”将test_n与后面的py分开,然后通过切片的方式将test从下面的数字中分离出来,最后通过拼接字符的方式将其改为test_n.py的新文件名形式。但是今天写的时候突然想到了另外一个方法,就是把文件名用我要替换的字符剪下来,然后用join。

  导入print(OS . listdir())file _ list=OS . listdir()for file in file _ list:if test in file:print(file . split( test ))new _ file= test _ 。join (file.split (test ))

  d:\ GitHub \自动重复\。venv \ Scripts \ python . exe D:/GitHub/auto-repeat/replace _ filename/main . py[ main . py , test1.py , test2.py , test3.py ,_ _ init _ _。py] [ , 1.py] test _ 1.py [ , 2.py] test _ 2.py [ , 3.py] test _ 3.py进程结束,退出代码为0。您可以看到被替换的文件名已被指定。

  最终代码如下:

  Import os#获取当前文件夹中所有文件和文件夹的列表file _ list=OS . listdir()for file in file _ list:if test in file:# Replace test new _ file= test _ 。join(file . split( test )#文件名带test _ to替换os.rename(file,new_file)扩展名:有时修改需要过滤只修改文件。

  使用os.path.isfile(文件)

  可能还需要判断文件后缀。

  file.endswith(。py’)

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: