程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python batch modify file name

編輯:Python

Here, take modifying the image file name as an example , Copy the picture to a new directory and change the name ~

The original file name is as follows

The modified effect is as follows

 

Here comes the code

# The implementation will one Copy every picture in the folder to two Folder and change the picture name to follow a、b、c、d Incremental sort
# Ideas : Rename to create a new file and copy the contents of the original file
import os
def alterFileName(source,target):
print(" There are several files under the current folder >>>")
file_list=os.listdir(source)
print(file_list)
os.mkdir(target)
print(os.getcwd()) # Get current directory
os.chdir(source) # If the directory is not modified here , To open the original file, you need to prefix the file name with the absolute path
print(os.getcwd())
ch='a'
for file in file_list:
name_list=file.rpartition('.') # Set the file name string as '.' section
t_name=target+'/'+ch+name_list[1]+name_list[2]
print(t_name)
f1=open(file,'rb')
f2=open(t_name,'wb')
while True:
content=f1.read(1024) # Read once 1KB
if content==b'':
print(f" The first {ord(ch)-96} Pictures copied >>>")
ch=chr(ord(ch)+1)
f1.close()
f2.close()
break
f2.write(content)
else:
print(f"{len(file_list)} All the pictures have been copied to {target} Under the folder !")
if __name__ == '__main__':
source_dir="D:\\PyProjects\\one" # use \\ perhaps / All possible
target_dir="D:/PyProjects/two"
alterFileName(source_dir,target_dir)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved