本文实例讲述了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程序设计有所帮助。

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

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


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1
強大的PHP整合開發環境

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器