Python rename files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os
import os.path

# point to the target directory
dirpath = 'F:\\a\\'

# loop begin
for file in os.listdir(dirpath):
# if it's a file
if os.path.isfile(os.path.join(dirpath, file)) == True:
newname = '[BOMB.tv]' + file
#rename it
os.rename(os.path.join(dirpath, file),os.path.join(dirpath, newname))
print (file,'ok')

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os
import sys

dirpath = 'F:\\a\\'

#three parameters: parent directory, all directory name, all file names
for parent,dirnames,filenames in os.walk(dirpath):
for filename in filenames:
# format output
old = "%s/%s" %(dirpath, filename)
new = "%s/%s" %(dirpath, "[BOMB.tv]" + filename)
os.rename(old, new)

# output directory info
for dirname in dirnames:
print ("parent is:" + parent)
print ("dirname is:" + dirname)

# output file info
for filename in filenames:
print ("parent is:" + parent)
print ("filename is:" + filename)
print ("the full name of the file is:" + os.path.join(parent,filename))