import os
# Create the file index include the sub directory
def create_file_index(index_file,path):
"""docstring for create_file_index"""
fnum = 0
# os.walk() can list the content of sub directory
for root, dirs, flist in os.walk(path):
for name in flist:
index_file.write(os.path.join(root,name)+"\n")
#print os.path.join(root,name)
fnum += len(flist)
index_file.write(str(fnum)+"\n")
print 'There are %d files, ceate index successfully!' % (fnum)
# delete the files in the index.txt
def del_from_index(index_file):
"""docstring for del_from_index"""
count = 0
for f in index_file:
f = f[:-1] # delete the '\n' at the end of each line
if os.path.isfile(f):
print 'delete file:' + f
os.remove(f)
count = count + 1
print 'Remove %d files done!' % (count)
if __name__=="__main__":
# Get the content of path, not include the content of sub directory
'''flist = os.listdir(path)
for f in flist:
print path + os.sep + f
'''
# create file index or delete file
choice = raw_input("create file index or delete file, c/d?:")
if choice == 'c':
# Get current directory
path = os.getcwd()
# Get the path that will be dealed
usr = raw_input("Input the directory name(e.g. usr):")
path = path + '/' + usr
print "The path is:"+path
# Create a file for store the file index
index_file = open("index.txt","w+")
create_file_index(index_file,path)
elif choice == 'd':
index_file = open("index.txt","r")
del_from_index(index_file)
index_file.close()
使用命令 $diff index.txt index_usr.txt > m.txt 将两次索引中文件的不同地方找出来存储到m.txt中,再利用下面的代码删除索引中不同的文件(即新增加的文件)
import os
import shutil
fp = open("m.txt","r")
for eachline in fp:
eachline = eachline[:-1] # remove \n
if eachline[0]=='<':
eachline = eachline[2:] #remove "< "
if os.path.isfile(eachline):
print 'current file:' + eachline
#shutil.copy(eachline,'/Users/Edison/code/usr/bin') #backup files
os.remove(eachline)
本文使用Blog_Backup未注册版本导出,请到soft.pt42.com注册。