本文实例讲述了Python比较文件夹比另一同名文件夹多出的文件并复制出来的方法。分享给大家供大家参考。具体如下:
这个东东本来是做来给公司数据同步用的:新服务器还没正式启用,旧的服务器还在使用,每天都有大量图片传到旧服务器上面,为了避免备份全部图片,所以写了这么个工具。
1. 运行效果如下图所示:
2. Python代码如下:
代码如下:
# coding=gbk
'''
Created on 2011-1-7
@author: HH
'''
import os,ConfigParser
'''
递归列出某目录下的文件,放入List中
'''
def listDir (fileList,path):
files=os.listdir(path)
for i in files:
file_path=path+"\\"+i
if os.path.isfile(file_path):
fileList.append(file_path)
for i in files:
file_path=path+"\\"+i
if os.path.isdir(file_path):
#fileList.append(file_path)
listDir(fileList,file_path)
return fileList
'''
将List中内容写入文件
'''
def writeListToFile(list,path):
strs="\n".join(list)
f=open(path,'wb')
f.write(strs)
f.close()
'''
读入文件内容并放入List中
'''
def readFileToList(path):
lists=[]
f=open(path,'rb')
lines=f.readlines()
for line in lines:
lists.append(line.strip())
f.close()
return lists
'''
比较文件--以Set方式
'''
def compList(list1,list2):
return list(set(list1)-set(list2))
'''
复制List中文件到指定位置
'''
def copyFiles(fileList,targetDir):
for file in fileList:
targetPath=os.path.join(targetDir,os.path.dirname(file))
targetFile=os.path.join(targetDir,file)
if not os.path.exists(targetPath):
os.makedirs(targetPath)
if not os.path.exists(targetFile) or (os.path.exists(targetFile) and os.path.getsize(targetFile)!=os.path.getsize(file)):
print "正在复制文件:"+file
open(targetFile,'wb').write(open(file,'rb').read())
else:
print "文件已存在,不复制!"
if __name__ == '__main__':
path=".svn"
#获取源目录
txtFile="1.txt"
#目录结构输出的目的文件
tdir="cpfile"
#复制到的目标目录
cfFile="config.ini";
#配置文件文件名
fileList=[]
#读取配置文件
if(os.path.exists(cfFile)):
cf=ConfigParser.ConfigParser()
cf.read(cfFile)
path=cf.get("main", "sourceDir")
txtFile=cf.get("main","txtFile")
tdir=cf.get("main","targetDir")
else:
print "配置文件不存在!"
raw_input("\n按 回车键 退出\n")
exit()
if(os.path.exists(txtFile)):
#如果导出的文件存在,就读取后比较
list1=readFileToList(txtFile)
print "正在读取文件列表……"
fileList=listDir (fileList,path)
print "正在比较文件……"
list_res=compList(fileList,list1)
if len(list_res)>0:
print "以下是原目录中不存在的文件:\n"
print "\n".join(list_res)
print "\n共计文件数:"+str(len(list_res))+"\n"
if raw_input("\n是否复制文件?(y/n)")!='n':
copyFiles(list_res,tdir)
else:
print "没有不相同的文件!"
else:
#如果导出的文件不存在,则导出文件
print "正在读取文件列表……"
fileList=listDir (fileList,path)
writeListToFile(fileList,txtFile)
print "已保存到文件:"+txtFile
raw_input("\n按 回车键 退出\n")
3. 配置文件名:config.ini如下:
代码如下:
#配置文件名:config.ini
[main]
sourceDir=wwwroot
txtFile=1.txt
targetDir=cp
希望本文所述对大家的Python程序设计有所帮助。

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
