python文件操作

python文件批量重命名操作

python批量更改文件名

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

def (path):
global count;
if not os.path.isfile(path) and not os.path.isdir(path):
return False;

if os.path.isfile(path):
filepath = os.path.split(path)
filename = os.path.splitext(filepath[-1])
file_ext = filename[-1]

if file_ext == '.txt':
os.rename(path, filepath[0]+'/'+'ex_'+str(count)+file_ext)
count += 1

elif os.path.isdir(path):
for x in os.listdir(path):
change_name(os.path.join(path, x))


count = 1
file_dir = 'C:/Users/lansheng/Desktop/py'
change_name(file_dir)

用md5查找文件夹下相同文件并删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import hashlib
from time import clock as now


def getmd5(filename):
file_txt = open(filename, 'rb').read()
md5 = hashlib.md5()
md5.update(file_txt)

return md5.hexdigest()


path = '.'
all_md5 = []
total_file = 0
delete_file = 0


def del_dump(path):
global total_file
global delete_file

for parent, dirnames, filenames in os.walk(path):
for filename in filenames:
total_file += 1
real_path = os.path.join(parent, filename)


filemd5 = getmd5(real_path)
if filemd5 in all_md5:
delete_file += 1
#do delete
os.remove(real_path)
print 'remove:',real_path

else:
all_md5.append(filemd5)

def del_emptydir(path):
if os.path.isdir(path):
for p in os.listdir(path):
d = os.path.join(path, p)
if(os.path.isdir(d) == True):
del_emptydir(d) #recursive
if not os.listdir(path):
os.rmdir(path)
print 'remove dir:', path


start = now()

del_dump(path)
#del_emptydir(path)

end = now()

time_last = end - start

print 'total file: ', total_file
print 'delete file: ', delete_file
print 'cost time: ', time_last, 's'