建立指定目录下文件的索引并删除

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注册。

转载于:https://www.cnblogs.com/aquar/archive/2010/12/27/3451401.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值